1、新建两个工程,TestWriteKeyChain和TestReadKeyChain; (添加Security.framework库,读取keychain要用到).然后添加苹果官方的KeychainItemWrapper.h和KeychainItemWrapper.m文件用于访问keychain。
2、更改两个工程的.plist文件的Bundle identifier分别为 com.companyname.app.TestWriteKeyChain和 com.companyname.app.TestReadKeyChain;
3、更改两个工程的Entitlements。在两个工程的Entitlements的Keychain Access Groups 添加上面两个Bundle identifier;如下图:
5、在TestWriteKeyChain工程中的
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 函数中添加下面的代码:
KeychainItemWrapper *keyChain = [[KeychainItemWrapperalloc]initWithIdentifier:@"_test_write_keychain_"accessGroup:nil];//注意accessGroup为nil,
//第一次读取,因为之前没设置,keychaindata应该为nil
id keychaindata = [keyChain objectForKey:(id)kSecAttrAccount];
NSLog(@"first keychaindata :%@, %@, %d",keychaindata, [keychaindataclass], [(NSString*)keychaindatalength]);
//向keychain写入相应数据,这里我们写一个字符串@"testwritekeychain"
[keyChain setObject:@"testwritekeychain" forKey:(id)kSecAttrAccount];
//第二次读取,因为之前没设置,keychaindata应该为@"testwritekeychain"
keychaindata = [keyChain objectForKey:(id)kSecAttrAccount];
NSLog(@"second keychaindata :%@, %@, %d",keychaindata, [keychaindata class], [(NSString *)keychaindatalength]);
运行TestWriteKeyChain后,在TestReadKeyChain中的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 函数中添加下面的代码:
KeychainItemWrapper *keyChain = [[KeychainItemWrapper alloc] initWithIdentifier:@"_test_write_keychain_" accessGroup:nil];
id keychaindata = [keyChain objectForKey:(id)kSecAttrAccount];
NSLog(@"first keychaindata :%@, %@, %d", keychaindata, [keychaindata class], [(NSString *)keychaindata length]);
应该也能读取到@"testwritekeychain"。