iOS: store userName, password and access token using keychain

867 Views Asked by At

I want to use keychain in order to store username, password and access token. I added the keychainItem.h and keyChainItem.m implemented here. And this is what I did:

1- I created a property keychain in myViewController.h then in the viewDidLoad I instantiate it like this:

self.keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"Login" accessGroup:nil];

When I got the userName, password and the access token this is what I did:

2- To store the userName

[self.keychain setObject:userName forKey:(__bridge id)kSecAttrAccount]; 

When I test it, it works.

Now I want to add the password and the access token.

For the access token I tried

[self.keychain setObject:accessToken forKey:(__bridge id)kSecAttrAccessible];

When I run it the application crash:

Assertion failure in -[KeychainItemWrapper writeToKeychain] KeychainItemWrapper.m:322
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Couldn't update the Keychain Item.'

I tried to create another keychain

self.keychainToken = [[KeychainItemWrapper alloc] initWithIdentifier:@“Token” accessGroup:nil];

then I set the value:

[self.keychainToken setObject:accessToken forKey:(__bridge id)kSecValueData]; 

But I got the same error.

What is wrong with what I did? How can I store the user, password and the accessToken using keychain?

1

There are 1 best solutions below

8
Poles On BEST ANSWER

You can use it like this:

self.keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"Login" accessGroup:nil];

[self.keychain setObject:userName forKey:(id)kSecAttrAccount];
[self.keychain setObject:password forKey:(__bridge id)(kSecValueData)];
[self.keychain setObject:accessToken forKey:(id)kSecAttrTokenID];
[self.keychain setObject:@"LoginService" forKey: (id)kSecAttrService];