get uuid with keychain

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface ZYFKeyChainForUUId : NSObject

+ (NSString *)getUUid;

@end

NS_ASSUME_NONNULL_END
#import "ZYFKeyChainForUUId.h"

@implementation ZYFKeyChainForUUId

+ (NSMutableDictionary *)getKeychainDic:(NSString *)key {
    return [[NSMutableDictionary alloc] initWithObjectsAndKeys:
            (id)kSecClassGenericPassword, (id)kSecClass,
            key,(id)kSecAttrService,
            key,(id)kSecAttrAccount,
            (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
            nil];
}

+ (void)add:(NSString *)key value:(id)data {
    NSMutableDictionary * mutDic = [self getKeychainDic:key];
    CFDictionaryRef ref = (__bridge CFDictionaryRef)mutDic;
    SecItemDelete(ref);
    NSData * d = [NSKeyedArchiver archivedDataWithRootObject:data requiringSecureCoding:YES error:nil];
    [mutDic setObject:d forKey:(id)kSecValueData];
    SecItemAdd(ref, NULL);
}

+ (void)delete:(NSString *)key {
    NSMutableDictionary *keychainQuery = [self getKeychainDic:key];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}

+ (NSString *)getUUid {
    NSString * key = @"z_key_uuid";
    id ret = nil;
    NSMutableDictionary * mutDict = [self getKeychainDic:key];
    [mutDict setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [mutDict setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    OSStatus status = SecItemCopyMatching((CFDictionaryRef)mutDict, (CFTypeRef *)&keyData);
    if (status == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData exception:nil];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", key, e);
        } @finally {
        }
    }
    if (!ret) {
        ret = [ZYFKeyChainForUUId UUID];
        [self add:key value:ret];
    }
    return (NSString *)ret;
}

+ (NSString *)UUID {
    CFUUIDRef puuid = CFUUIDCreate(nil);
    CFStringRef uuidString = CFUUIDCreateString(nil, puuid);
    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy(NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    return result;
}

@end

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容