已成功将String值存储到钥匙串,但始终无法读取它 [英] Successfully stored String value to keychain, but always failed to read it out

查看:98
本文介绍了已成功将String值存储到钥匙串,但始终无法读取它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用XCode8 + Swift3开发一个iOS项目.

I am developing an iOS project with XCode8 + Swift3.

我创建了以下两个函数来将字符串存储到钥匙串中并从钥匙串中读取它:

I have created the following two functions to store string to keychain and read it back from keychain:

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

}

我调用函数:

boolean hasStored = storeString(value: "John")
let readVal = readString()

我得到的hasStoredtrue,但是readVal总是nil.我调查了我的函数,发现我总是在读取器函数中得到错误-50作为状态代码(请参见函数中的注释).

I got hasStored is true, but readVal always nil. I investigated my functions, I see I always get error -50 as status code in reader function (see my comment in my function).

为什么?为什么我无法读取存储在钥匙串中的值(我不确定它是否确实存储了,但是我确实得到status == noErr总是在storeString(value:)函数中重新调整true)

Why? Why I can't read the value I stored in keychain (I am not sure whether it is really stored but I do get status == noErr always retuns true in storeString(value:) function)

推荐答案

您的代码中有错字:

query[kSecMatchLimit as String] = kSecMatchLimit
//                                ^~~~~~~~~~~~~~

kSecMatchLimit是键,不是有效值.期望值应为CFNumberkSecMatchLimitOnekSecMatchLimitAll.如果希望返回单个项目,请使用kSecMatchLimitOne.另请参见搜索属性键和值.

kSecMatchLimit is the key and not a valid value. The expected value should be a CFNumber or kSecMatchLimitOne or kSecMatchLimitAll. If you expect a single item to be returned, use kSecMatchLimitOne. See also Search Attribute Keys and Values.

这篇关于已成功将String值存储到钥匙串,但始终无法读取它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆