Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem using KeychainItemWrapper

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?

like image 652
Anh Avatar asked Aug 29 '10 16:08

Anh


1 Answers

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];
like image 77
Viraj Avatar answered Oct 17 '22 01:10

Viraj