钥匙串可存储少量数据,常用于App删除后数据依然存储在本地的需求
1.增(存储)
+ (void)saveWithService:(NSString *)service Account:(NSString *)account Password:(NSString *)password
{
NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *saveSecItems = @{(id)kSecClass: (id)kSecClassGenericPassword,
(id)kSecAttrService: service,
(id)kSecAttrAccount: account,
(id)kSecValueData: passwordData
};
SecItemAdd((CFDictionaryRef)saveSecItems, NULL);
}
2.查
+ (NSString *)queryWithService:(NSString *)service Account:(NSString *)account
{
NSDictionary *matchSecItems = @{
(id)kSecClass: (id)kSecClassGenericPassword,
(id)kSecAttrService: service,
(id)kSecAttrAccount: account,
(id)kSecMatchLimit: (id)kSecMatchLimitOne,
(id)kSecReturnData: @(YES)
};
CFTypeRef dataRef = nil;
OSStatus errorCode = SecItemCopyMatching((CFDictionaryRef)matchSecItems, (CFTypeRef *)&dataRef);
if (errorCode == errSecSuccess) {
NSString *password = [[NSString alloc] initWithData:CFBridgingRelease(dataRef) encoding:NSUTF8StringEncoding];
return password;
}
return nil;
}
3.改
+ (void)updateWithService:(NSString *)service Account:(NSString *)account Password:(NSString *)password
{
NSDictionary *queryItems = @{(id)kSecClass: (id)kSecClassGenericPassword,
(id)kSecAttrService: service,
(id)kSecAttrAccount: account
};
NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *updatedItems = @{
(id)kSecValueData: passwordData,
};
SecItemUpdate((CFDictionaryRef)queryItems, (CFDictionaryRef)updatedItems);
}
4.删
+ (void)deleteWithService:(NSString *)service Account:(NSString *)account
{
NSDictionary *deleteSecItems = @{
(id)kSecClass: (id)kSecClassGenericPassword,
(id)kSecAttrService: service,
(id)kSecAttrAccount: account
};
SecItemDelete((CFDictionaryRef)deleteSecItems);
}
参考
iOS 钥匙串的基本使用
网友评论