Save data in keychain from one iOS app and access it from another iOS app (Xcode 5) !
Creating your first app that will write to the Keychain
Settings for project :
- Add the Security.framework to your project.
- Download UICKeyChainStore and add the UICKeyChainStore.h and UICKeyChainStore.m files from Lib folder to your project.
- Go to Target -> Capabilities -> Keychain Sharing. By default it is off. On this option.
- As you will on it, a file name projectName.entitlements will add in your "Project Navigator", with key "Keychain Access Groups" of type "Array" with one "Item" of type "String" and Value "$(AppIdentifierPrefix)$(CFBundleIdentifier)". For example : com.my.firstApp is the Bundle identifier then Value will be "$(AppIdentifierPrefix)com.my.firstApp". It will look like this :
Now all you need to do is start using the UICKeyChainStore and you'll be saving data to the KeyChain.
Now, in your class import "UICKeyChainStore.h" and write the following code:
[UICKeyChainStore setString:@"mySecretPassword" forKey:@"password" service:@"MyService"];
[UICKeyChainStore stringForKey:@"password" service:@"MyService"];
Specifying the service allows you to store keys for a particular service, maybe you have a Twitter or Facebook specific set of keys you wish to save.
As you can see we are not specifying the accessGroup. By default it will pick the first access-group specified in your projectName.entitlements when writing and will search across all access-groups when none is specified.
Allowing your second app to access your shared keychain data:
Settings for project :
- Repeat above steps from 1 to 3 (for firstApp). It will look like this :
We want access to the Keychain group $(AppIdentifierPrefix)com.my.firstApp for reading, but we still want the default writing to occur in our own keychain group so we still specify $(AppIdentifierPrefix)com.my.secondApp as the first / default group. Add one more item in "Keychain Access Groups" with Value $(AppIdentifierPrefix)com.my.firstApp
It will look like this:
Now, read the value from the shared Keychain exactly how we did in our first app.
In your class import "UICKeyChainStore.h" and write the following code:
[UICKeyChainStore stringForKey:@"password" service:@"MyService"];
This should return the value “mySecretPassword” :)
Happy Coding :)
No comments:
Post a Comment