我使用以下代码从iPhone钥匙串中检索登录凭据:
KeychainItemWrapper *wrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"Test" accessGroup:nil];
NSString *username = [wrapper objectForKey:(id)kSecAttrAccount];
NSString *password = [wrapper objectForKey:(id)kSecValueData];
[wrapper release];
Run Code Online (Sandbox Code Playgroud)
我的第一次用户启动应用程序,无论用户名密码也可以从钥匙串中检索的印象,所以username和password应该等于nil.但是,我无法使用打印出任何这些变量NSLog.
有什么建议?
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];
Run Code Online (Sandbox Code Playgroud)
小智 5
您的假设是错误的 - 在创建时,"kSecAttrAccount"和"kSecValueData"未设置为nil.它们被设置为空字符串(即"").所以,这段代码将返回true:
[username isEqualToString:@""] // returns true on creation
Run Code Online (Sandbox Code Playgroud)