ios-keychain数据共享

2018-03-21  本文已影响56人  简鱼7819

ios设置keychain  sharing,可以实现跨应用存取数据。

一、设置

在工程的Capabilities-->keychain  sharing

点击“+”号

将你想要共享的工程bundleID添加进去

注:发者不同,不影响keychain数据共享

二、keychain代码

数据的处理无所谓就是四种增删改查四种,写到代码基本上就三样,增改、删除、读取。

增改

+ (void)save:(NSString *)service account:(NSString *)account data:(id)data {

//Get search dictionary

NSMutableDictionary *keychainQuery = [self getKeychainQuery:service account:account];

//Delete old item before add new item SecItemDelete((CFDictionaryRef)keychainQuery);

//Add new object to search dictionary(Attention:the data format)

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

//Add item to keychain with the search dictionary SecItemAdd((CFDictionaryRef)keychainQuery, NULL);

}

读取

+ (id)load:(NSString *)service account:(NSString *)account{

id ret = nil;

NSMutableDictionary *keychainQuery = [self getKeychainQuery:service account:account];

//Configure the search setting

//Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData]; [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit]; CFDataRef keyData = NULL;

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

                @try { ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData]; }

                @catch (NSException *e) { NSLog(@"Unarchive of %@ failed: %@", service, e); }

               @finally { }

        }

        if (keyData) CFRelease(keyData);

        return ret;

}

删除

+ (void)deleteKeyData:(NSString *)service account:(NSString *)account{

NSMutableDictionary *keychainQuery = [self getKeychainQuery:service account:account]; 

 SecItemDelete((CFDictionaryRef)keychainQuery);

}

其中getKeychainQuery函数

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

return [NSMutableDictionary dictionaryWithObjectsAndKeys:                              (id)kSecClassGenericPassword,

(id)kSecClass, service,

(id)kSecAttrService, account,

(id)kSecAttrAccount,

(id)kSecAttrAccessibleAfterFirstUnlock,

(id)kSecAttrAccessible, nil];

}

三、总结

多个应用共享keychain数据,在keychain Groups中添加多条BundleID,keychain数据会被共享,只要填写的service和account参数一致,一个应用数据被删除或者篡改,另外的应用对应读取的keychain都会变化。

keychain数据共享不受开发者影响,同时该数据做到了跨应用!

上一篇下一篇

猜你喜欢

热点阅读