#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
网友评论