views:

104

answers:

2

I use the following code to retrieve the login credentials from the iPhone keychain:

KeychainItemWrapper *wrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"Test" accessGroup:nil];
NSString *username = [wrapper objectForKey:(id)kSecAttrAccount];
NSString *password = [wrapper objectForKey:(id)kSecValueData];
[wrapper release];

I'm under the impression that the first time a user launches the app, neither username nor password could be retrieved from the keychain, so username and password should be equal to nil. I, however, was unable to print out any of these variables using NSLog.

Any suggestions?

+1  A: 
KeychainItemWrapper *wrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"Test" accessGroup:nil];
NSString *username = [wrapper objectForKey:(id)kSecAttrAccount];
NSString *password = [wrapper objectForKey:(id)kSecValueData];

// initially all these are empty
NSLog(@"username - %@", username); // username - 
NSLog(@"password - %@", password); // password - 

//if empty set your credentials
if ( [username isEqualToString:@""] ) {
    [wrapper setObject:@"your username here" forKey:(id)kSecAttrAccount];
}
if ( [password isEqualToString:@""] ) {
    [wrapper setObject:@"your password here" forKey:(id)kSecValueData];
}

//get the latest credentials - now you have the set values
username = [wrapper objectForKey:(id)kSecAttrAccount];
password = [wrapper objectForKey:(id)kSecValueData];

NSLog(@"username - %@", username); // username - your username here
NSLog(@"password - %@", password); // password - your password here

// reset your keychain items - if  needed
[wrapper resetKeychainItem];
[wrapper release];
Viraj
The part I'm not sure about is "initially all these are empty". As mentioned in my question, I couldn't get `NSLog` to print any of these values. I'm trying to bring up the login dialog if they're empty/nil, but it doesn't work.
QAD
A: 

I think your Identifier needs "com." in the name.