尝试在安全链中添加项目时,请继续获取-50。
var query = [String:AnyObject]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecAttrAccount as String] = "a"
query[kSecValueData as String] = "b"
let result = SecItemAdd(query as CFDictionary, nil);
结果是-50。无法弄清楚原因,需要帮助..提前谢谢。
答案 0 :(得分:8)
我认为<%= link_to "Back to Top", '#top_of_blogs_list' %>
密钥的值必须是NSData,而不是String或NSString。尝试将字符串编码为数据(例如使用UTF-8编码)。未经测试的代码段:
kSecValueData
为了将来参考,错误代码-50对应于query[kSecValueData as String] = "b".dataUsingEncoding(NSUTF8StringEncoding)
,SecBase.h头文件的含义为:“传递给函数的一个或多个参数无效。”如果再次看到此错误,请尝试使用查询字典更改传入的值。
答案 1 :(得分:0)
稍作更新的Swift 5版本的“添加/删除钥匙串”功能:
@discardableResult
func addToKeychain(_ value: Data, tag: Data) -> Bool {
let attributes: [String: Any] = [
String(kSecClass): kSecClassKey,
String(kSecAttrApplicationTag): tag,
String(kSecValueData): value
]
var result: CFTypeRef? = nil
let status = SecItemAdd(attributes as CFDictionary, &result)
if status == errSecSuccess {
print("Successfully added to keychain.")
} else {
if let error: String = SecCopyErrorMessageString(status, nil) as String? {
print(error)
}
return false
}
return true
}
@discardableResult
func removeFromKeychain(_ value: Data, tag: Data) -> Bool {
let attributes: [String: Any] = [
String(kSecClass): kSecClassKey,
String(kSecAttrApplicationTag): tag,
String(kSecValueData): value
]
let status = SecItemDelete(attributes as CFDictionary)
if status == errSecSuccess {
print("Successfully removed from keychain.")
} else {
if let error: String = SecCopyErrorMessageString(status, nil) as String? {
print(error)
}
return false
}
return true
}
可以这样使用:
let value: Data = "key".data(using: .utf8)!
let tag: Data = "com.test.key".data(using: .utf8)!
removeFromKeychain(value, tag: tag)
addToKeychain(value, tag: tag)