And*_*nez 5 keychain security-framework ios ios7
由于某种原因,我无法让这个简单的钥匙串代码工作。
//Let's create an empty mutable dictionary:
NSMutableDictionary *keychainItem = [NSMutableDictionary dictionary];
NSString *username = self.nwUsernameTxtFld.text;
NSString *password = self.passwordTxtFld.text;
//Populate it with the data and the attributes we want to use.
keychainItem[(__bridge id)kSecClass] = (__bridge id)kSecClassInternetPassword; // We specify what kind of keychain item this is.
keychainItem[(__bridge id)kSecAttrAccessible] = (__bridge id)kSecAttrAccessibleWhenUnlocked; // This item can only be accessed when the user unlocks the device.
keychainItem[(__bridge id)kSecAttrServer] = @"http://www.myawesomeservice.com";
keychainItem[(__bridge id)kSecAttrAccount] = username; //Our username.
if(SecItemCopyMatching((__bridge CFDictionaryRef)keychainItem, NULL) == noErr)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"The Item Already Exists", nil)
message:NSLocalizedString(@"Please update it instead.", )
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", nil)
otherButtonTitles:nil];
[alert show];
}else
{
NSLog(@"can add new item.");
keychainItem[(__bridge id)kSecValueData] = password; //Our password
OSStatus sts = SecItemAdd((__bridge CFDictionaryRef)keychainItem, NULL);
NSLog(@"%d", (int)sts);
}
Run Code Online (Sandbox Code Playgroud)
我查了苹果公司关于此事的文档,根据它:
传递给函数的一个或多个参数无效。
然而,该SecAddItem函数有两个参数:
OSStatus SecItemAdd (
CFDictionaryRef attributes,
CFTypeRef *result
);
Run Code Online (Sandbox Code Playgroud)
我将 NULL 传递给结果。根据Apple的文档,这是可以接受的:
结果 返回时,对新添加的项目的引用。结果的确切类型基于属性中提供的值,如下所述。如果不需要此结果,则传递 NULL。
所以我真的不知道我在这里做错了什么。我向它传递一个字典和一个 NULL 值。该函数需要两者,而我两者都给了它。有人可以告诉我出了什么问题吗?
作为参考,文档位于此处。
您正在将不正确的数据类型插入到 key 的字典中kSecValueData。正如问题底部的文档所示,它需要CFDataRef(或桥接NSData),但您要插入一个NSString。NSString转换是一件微不足道的事情,NSData一旦你这样做了,你就不会再出现这个错误了。
| 归档时间: |
|
| 查看次数: |
2552 次 |
| 最近记录: |