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>

@implementation AppDelegate

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions:(NSDictionary *)

Get iOS 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.