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 钥匙串的基本使用

 

人已赞赏
iOS文章

AFNetworking接收text/plain

2019-10-15 14:12:07

iOS文章

iOS 使用AFNetWorking进行多张图片上传

2019-10-15 16:43:32

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索