PassionateDeveloper
PassionateDeveloper

Reputation: 15138

Keychain doesn't get data

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?

Upvotes: 0

Views: 1916

Answers (1)

Joe
Joe

Reputation: 57169

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];

Upvotes: 5

Related Questions