行。我在视图控制器中设置了用户密码:
KeychainItemWrapper *keychainWrapper =
[[KeychainItemWrapper alloc] initWithIdentifier:
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"] accessGroup:nil];
[keychainWrapper setObject:@"theUser" forKey:(__bridge id)(kSecAttrAccount)];
[keychainWrapper setObject:_passcode forKey:(__bridge id)(kSecValueData)];
NSLog(@"Saved pass: %@",_passcode);
NSLog(@"Returned pass: %@",[keychainWrapper objectForKey:(__bridge id)(kSecValueData)]);
NSlogs返回我设置的相同字符串,让我们假设它是1234.稍后在AppDelegate中我尝试检索密码:
KeychainItemWrapper *keychainWrapper =
[[KeychainItemWrapper alloc] initWithIdentifier:
[[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleIdentifier"] accessGroup:nil];
passcodeViewController.passcode = [keychainWrapper objectForKey:(__bridge id)(kSecValueData)];
NSLog(@"Pass: %@",[keychainWrapper setObject:_passcode forKey:(__bridge id)(kSecValueData)]);
然后邪恶来了。 NSLog返回:31323334。我做错了什么?
答案 0 :(得分:2)
Keychain将密码存储为NSData
,而不是NSString
。在存储密码之前,您需要对其进行编码。
NSData * passcodeData = [_passcode dataUsingEncoding:NSUTF8StringEncoding];
[keychainWrapper setObject:passcodeData forKey:(__bridge id)(kSecValueData)];
同样,检索到的对象是您需要解码的NSData
。
NSData * passcodeData = [keychainWrapper objectForKey:(__bridge id)(kSecValueData)];
passcodeViewController.passcode = [[NSString alloc] initWithBytes:[passcodeData bytes]
length:[passcodeData length]
encoding:NSUTF8StringEncoding];