有些数据需要记录在钥匙中:亲测可用
首先要导入
#import <Security/Security.h>
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
return [NSMutableDictionary dictionaryWithObjectsAndKeys:
( id)kSecClassGenericPassword,
( id)kSecClass,service,
( id)kSecAttrService,service,
( id)kSecAttrAccount,
( id)kSecAttrAccessibleAfterFirstUnlock,
( id)kSecAttrAccessible,
nil];
}
+ (void)saveKeychainValue:(NSString *)sValue key:(NSString *)sKey {
NSMutableDictionary * keychainQuery = [self getKeychainQuery:sKey];
SecItemDelete(( CFDictionaryRef)keychainQuery);
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:sValue] forKey:( id)kSecValueData];
SecItemAdd(( CFDictionaryRef)keychainQuery, NULL);
}
+ (NSString *)readKeychainValue:(NSString *)sKey {
NSString *ret = nil;
NSMutableDictionary *keychainQuery = [self getKeychainQuery:sKey];
[keychainQuery setObject:(id)kCFBooleanTrue forKey:( id)kSecReturnData];
[keychainQuery setObject:( id)kSecMatchLimitOne forKey:( id)kSecMatchLimit];
CFDataRef keyData = NULL;
if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
@try {
ret = (NSString *)[NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
} @catch (NSException *e) {
NSLog(@"Unarchive of %@ failed: %@", sKey, e);
} @finally {
}
}
if (keyData)
CFRelease(keyData);
return ret;
}
+ (void)deleteKeychainValue:(NSString *)sKey {
NSMutableDictionary *keychainQuery = [self getKeychainQuery:sKey];
SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
}
网友评论