美文网首页
【OC】钥匙串使用

【OC】钥匙串使用

作者: alanim | 来源:发表于2019-02-22 15:31 被阅读0次
    钥匙串可存储少量数据,常用于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);
    }
    

    Demo代码

    参考
    iOS 钥匙串的基本使用

    相关文章

      网友评论

          本文标题:【OC】钥匙串使用

          本文链接:https://www.haomeiwen.com/subject/pkeeyqtx.html