How to check if something is stored in the iPhone keychain?
iphone, keychain, sdk
Solution
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.
Problem
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]; ```