3

I have this code currently storing the information into the iPhone keychain. How can I check with a simple if statement if there is something under the same name already stored there to prevent double storage and to tell me if this is the first time the user is using the app?

KeychainItemWrapper* keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"KeychainTest" accessGroup:nil];
        [keychain setObject:username.text forKey:(__bridge id)(kSecAttrAccount)];
        [keychain setObject:password.text forKey:(__bridge id)(kSecValueData)];
        keychain = nil;

        usernameAll = [keychain objectForKey:(__bridge id)kSecAttrAccount];
        passwordAll = [keychain objectForKey:(__bridge id)kSecValueData];
ranjha
  • 91
  • 1
  • 13
  • possible duplicate of [iOS: How to store username/password within an app?](http://stackoverflow.com/questions/6972092/ios-how-to-store-username-password-within-an-app) – Jack Humphries Mar 20 '13 at 05:19

1 Answers1

4

You won't cause double storage. You will overwrite any existing value.

Create your keychain object, then call objectForKey:. If the result is nil then you know that there is no existing value for the key.

KeychainItemWrapper* keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"KeychainTest" accessGroup:nil];
if ([keychain objectForKey:(__bridge id)(kSecAttrAccount)]) {
    // existing value
} else {
    // no existing value
}

Checking to see if a user is using an app for the first time is usually done by writing a value to NSUserDefaults the first time the app is used. On startup, this value is checked. If the value exists, it's not the first run. If you need this check to survive an app deletion and reinstall, then use the keychain instead of NSUserDefaults to store this flag.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Hey, i have tested above code if values are getting stored in keychain or not. But above code is going in `if` condition, but i'm not getting value using `[keychain objectForKey:(__bridge id)(kSecAttrAccount)]`. What could be the reason ? – Uniruddh Nov 14 '13 at 12:56
  • @I-droid If you have a question, please post your own question. – rmaddy Nov 14 '13 at 15:01
  • here it is: http://stackoverflow.com/questions/19978563/unable-to-store-values-in-keychain-correctly – Uniruddh Nov 15 '13 at 06:53
  • Note that this approach does not work for Touch ID protected Keychain items - to fetch the value, you need to authenticate with Touch ID... – Petr Dvořák Sep 22 '16 at 09:20