Store NSDictionary in keychain

malinois picture malinois · Mar 30, 2012 · Viewed 12.5k times · Source

It is possible to store a NSDictionary in the iPhone keychain, using KeychainItemWrapper (or without)? If it's not possible, have you another solution?

Answer

Bret Deasy picture Bret Deasy · Nov 15, 2012

You must properly serialize the NSDictionary before storing it into the Keychain. Using:

[dic description]
[dic propertyList]

you will end up with a NSDictionary collection of only NSString objects. If you want to maintain the data types of the objects, you can use NSPropertyListSerialization.

KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"arbitraryId" accessGroup:nil]
NSString *error;
//The following NSData object may be stored in the Keychain
NSData *dictionaryRep = [NSPropertyListSerialization dataFromPropertyList:dictionary format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
[keychain setObject:dictionaryRep forKey:kSecValueData];

//When the NSData object object is retrieved from the Keychain, you convert it back to NSDictionary type
dictionaryRep = [keychain objectForKey:kSecValueData];
NSDictionary *dictionary = [NSPropertyListSerialization propertyListFromData:dictionaryRep mutabilityOption:NSPropertyListImmutable format:nil errorDescription:&error];

if (error) {
    NSLog(@"%@", error);
}

The NSDictionary returned by the second call to NSPropertyListSerialization will maintain original data types within the NSDictionary collection.