美文网首页
钥匙串~存取删

钥匙串~存取删

作者: 小七霏雨 | 来源:发表于2018-03-22 15:24 被阅读0次

    有些数据需要记录在钥匙中:亲测可用

    首先要导入 

    #import <Security/Security.h>

    + (NSMutableDictionary *)getKeychainQuery:(NSString *)service {

        return [NSMutableDictionary dictionaryWithObjectsAndKeys:

                ( id)kSecClassGenericPassword,

                ( id)kSecClass,service,

                ( id)kSecAttrService,service,

                ( id)kSecAttrAccount,

                ( id)kSecAttrAccessibleAfterFirstUnlock,

                ( id)kSecAttrAccessible,

                nil];

    }

    + (void)saveKeychainValue:(NSString *)sValue key:(NSString *)sKey {

        NSMutableDictionary * keychainQuery = [self getKeychainQuery:sKey];

        SecItemDelete(( CFDictionaryRef)keychainQuery);

        [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:sValue] forKey:( id)kSecValueData];

        SecItemAdd(( CFDictionaryRef)keychainQuery, NULL);

    }

    + (NSString *)readKeychainValue:(NSString *)sKey {

        NSString *ret = nil;

        NSMutableDictionary *keychainQuery = [self getKeychainQuery:sKey];

        [keychainQuery setObject:(id)kCFBooleanTrue forKey:( id)kSecReturnData];

        [keychainQuery setObject:( id)kSecMatchLimitOne forKey:( id)kSecMatchLimit];

        CFDataRef keyData = NULL;

        if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {

            @try {

                ret = (NSString *)[NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];

            } @catch (NSException *e) {

                NSLog(@"Unarchive of %@ failed: %@", sKey, e);

            } @finally {

            }

        }

        if (keyData)

            CFRelease(keyData);

        return ret;

    }

    + (void)deleteKeychainValue:(NSString *)sKey {

        NSMutableDictionary *keychainQuery = [self getKeychainQuery:sKey];

        SecItemDelete((__bridge CFDictionaryRef)keychainQuery);

    }

    相关文章

      网友评论

          本文标题:钥匙串~存取删

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