18

I'm using the ARCified version of KeychainItemWrapper available at github, and I can't get it to store both email and password.

KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"myApp" accessGroup:@"MY_APP.com.yourcompany.GenericKeychainSuite"];
    [keychainItem setObject:[self.email dataUsingEncoding:NSUTF8StringEncoding] forKey:(__bridge id)kSecAttrAccount];
    [keychainItem setObject:self.password forKey:(__bridge id)kSecValueData];    

I works perfectly as long as I store an email... that don't have an at sign (@) it. Otherwise, I get the error

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

Which comes from those lines

result = SecItemAdd((__bridge CFDictionaryRef)[self dictionaryToSecItemFormat:keychainItemData], NULL);
NSAssert( result == noErr, @"Couldn't add the Keychain Item." );

Do you have any idea about what can be going wrong here ?

Thanks

itzmebibin
  • 9,199
  • 8
  • 48
  • 62
Arnaud
  • 17,268
  • 9
  • 65
  • 83

2 Answers2

38

Well, I just found the answer following the advice on that page iOS KeychainItemWrapper not updating, which is to add

[keychainWrapper setObject:@"Myappstring" forKey: (id)kSecAttrService];
Community
  • 1
  • 1
Arnaud
  • 17,268
  • 9
  • 65
  • 83
  • 1
    KeychainItemWrapper was mostly working for me, worked on many email addresses (stored as username in kSecAttrAccount), but one email in particular did not work. I then added the above line for kSecAttrService and all is now perfect! -Thank you @user229688 – dbDev Feb 11 '13 at 21:24
  • Thanks user229688. It works perfectly after setting object for kSecAttrService – iOSAppDev May 06 '13 at 07:36
  • 1
    Note that you have to set that before you set kSecAttrAccount and kSecValueData. Otherwise it will still crash. – Hlung Aug 09 '13 at 11:32
  • How do retrieve this when next run of application? – Heena Aug 12 '13 at 11:01
  • I added that line of code before my line where I set kSecAttrAccount, and now it crashes on your line of code instead. Anyone else experiencing this? – HGDev Jul 07 '14 at 15:58
1

I know its an old question, but that was happening to me and the above answers did not fix my problem. In my case I was accessing the keychain when the phone was locked. Finally I got to solve it by using this just after init the keychain.

keychainWrapper.setObject(kSecAttrAccessibleAlways, forKey: kSecAttrAccessible)

It seems that keychain does not let you access it unless your phone is unlocked, by default.

More info here : http://b2cloud.com.au/tutorial/using-the-keychain-to-store-passwords-on-ios/

  • Interesting thanks for the input, although it's not advisable to always use that since it's less secure – Arnaud May 19 '16 at 09:36