Lee*_*fin 2 keychain ios swift3
我正在使用XCode8 + Swift3开发一个iOS项目。
我创建了以下两个函数来将字符串存储到钥匙串中并从钥匙串中读取它:
var query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "my service",
kSecAttrAccount as String: "my-key"
]
func storeString(value: String) -> Bool {
if let data = value.data(using: .utf8) {
// delete data if exist
SecItemDelete(query as CFDictionary)
// add value to query
query[kSecValueData as String] = data
// add to keychain
let status = SecItemAdd(query as CFDictionary, nil)
return status == noErr
}
return false
}
func readString() -> String? {
// update query
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecMatchLimit as String] = kSecMatchLimit
var result: AnyObject?
// fetch items from keychain
let status: OSStatus = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
// I always get error -50 here
if status == noErr {
if let resultData = result as? Data {
if let strVal = String(data: resultData, encoding: .utf8) {
return strVal
}
}
}
return nil
}
Run Code Online (Sandbox Code Playgroud)
我调用这些函数:
boolean hasStored = storeString(value: "John")
let readVal = readString()
Run Code Online (Sandbox Code Playgroud)
我hasStored就是true,但readVal始终nil。我调查了我的函数,发现在读取器函数中总是收到错误-50作为状态码(请参见函数中的注释)。
为什么?为什么我看不到我存储在钥匙串中的值(我不确定它是否确实存储了,但是我的确status == noErr总是true在storeString(value:)函数中进行调整)
您的代码中有一个错字:
query[kSecMatchLimit as String] = kSecMatchLimit
// ^~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
kSecMatchLimit是键,不是有效值。期望值应为CFNumber或kSecMatchLimitOne或kSecMatchLimitAll。如果您希望退回单个物品,请使用kSecMatchLimitOne。另请参阅搜索属性键和值。
| 归档时间: |
|
| 查看次数: |
206 次 |
| 最近记录: |