Security 框架
// 第一步:根据ServiceID获取对应配置
- (NSMutableDictionary *)getKeyChainQueryByServiceID:(NSString *)serviceID {
//这个就和keychainitemwrapper里面提前预设了参数一样
return [NSMutableDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassGenericPassword,(id)kSecClass,
serviceID,(id)kSecAttrService,
serviceID,(id)kSecAttrAccount,
(id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
nil];
}
// 第二步:存
- (void)saveObject:(id)obj toService:(NSString *)serviceID
{
//Get search dictionary
NSMutableDictionary *keychainQuery = [self getKeyChainQueryByServiceID:serviceID];
//Delete old item before add new item
SecItemDelete((CFDictionaryRef)keychainQuery);
//Add new object to search dictionary(Attention:the data format)
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:obj requiringSecureCoding:YES error:nil] forKey:(id)kSecValueData];
;
//Add item to keychain with the search dictionary
SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}
// 第三步:取
- (id)fetService:(NSString*)serviceID {
id ret = nil;
NSMutableDictionary *keychainQuery = [self getKeyChainQueryByServiceID:serviceID];
[keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
[keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
NSData *keyData = NULL;
if(SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef*)(void*)&keyData) == noErr) {
@try {
ret = [NSKeyedUnarchiver unarchivedObjectOfClass:[NSString class] fromData:keyData error:nil];
}
@catch (NSException *exception) {
}
@finally {
}
}
return ret;
}