OC 钥匙串使用

热门标签

,

特别声明:文章多为网络转载,资源使用一般不提供任何帮助,特殊资源除外,如有侵权请联系!

钥匙串可存储少量数据,常用于App删除后数据依然存储在本地的需求

service可以随意取,用于辨别哪个服务保存

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);
}

Demo代码

参考
iOS 钥匙串的基本使用

 

标签:

未经允许不得转载:作者:SheaYang, 转载或复制请以 超链接形式 并注明出处 技术Dog|博客
原文地址:《OC 钥匙串使用》 发布于2019-10-15

分享到:
赞(0)

评论 抢沙发

8 + 3 =


OC 钥匙串使用

长按图片转发给朋友

Vieu4.0主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。

登录

忘记密码 ?

您也可以使用第三方帐号快捷登录

Q Q 登 录
微 博 登 录