0

I use the common Keychain-wrapper from here: iOS: How to store username/password within an app?

Here is my Set-Code:

    KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"Animex" accessGroup:nil];
[keychain setObject:username forKey:@"Username"];
[keychain setObject:password forKey:@"Password"];

[keychain release];

Here is my Get-Code:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *password = [prefs stringForKey:@"Password"];

if ([password length] != 0)
{
    return password;
}
else
{
    return nil;
}

I only get NIL back, what am I doing wrong?

Community
  • 1
  • 1
PassionateDeveloper
  • 14,558
  • 34
  • 107
  • 176

1 Answers1

5

You are storing the values using KeychainItemWrapper then trying to retrieve them using NSUserDefaults. Those are 2 completely different backing stores so you need to use KeychainItemWrapper to retrieve your values. Also you should use kSecValueData and kSecAttrAccount.

The article you linked to actually has the answer in there.

//Set
KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"Animex" accessGroup:nil];
[keychain setObject:username forKey:kSecAttrAccount];
[keychain setObject:password forKey:kSecValueData];

[keychain release];


//Retrieve
KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"Animex" accessGroup:nil];
NSString *password = [keychainItem objectForKey:kSecValueData];

if ([password length] != 0)
{
    return password;
}
else
{
    return nil;
}
[keychain release];
Joe
  • 56,979
  • 9
  • 128
  • 135
  • Hi Joe, does it matter if I store the password for key `kSecValueData`? I've seen many examples online where users are storing usernames/passwords the other way around to how you have done. Is there an incorrect way? – sooper Mar 31 '12 at 23:11
  • @Sooper I posted them backwards in the first example, I apologize for that. – Joe Apr 03 '12 at 22:48