8.7. Writing to and Reading Keychain Data from iCloud
Problem
You want to store data in the keychain and have that data stored in the user’s iCloud keychain so that it will be available on all her devices.
Solution
When adding your item to the keychain using the SecItemAdd function, add the kSecAttrSynchronizable key to the dictionary
that you pass to that function. For the value of this key, pass kCFBooleanTrue.
Discussion
When items are stored in the keychain with their kSecAttrSynchronizable key set to kCFBooleanTrue, they will be stored in the
user’s iCloud keychain. This means that the items will be available on
all the user’s devices as long as she is logged into them using her
iCloud account. If you want to simply read a value that you know is
synchronized to the user’s iCloud keychain, you need to specify the
aforementioned key and the kCFBooleanTrue for this key as well, so that
iOS will retrieve that value from the cloud if it hasn’t already done
so.
The example that we are going to see here is 99% similar to the
example code that we saw in Recipe 8.6. The difference
is that, when we store or try to read from the keychain, we specify the
kSecAttrSynchronizable in our
dictionary and set the value of this key to kCFBooleanTrue. So let’s have a look at how we
can store the value in the keychain first:
#import "AppDelegate.h"#import <Security/Security.h>@implementationAppDelegate-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access