简记 swift 存储到钥匙串 实现app卸载重装保留数据

把数据存在钥匙串,可以在用户卸载重装后,仍然保留卸载前的数据。本文简单记录一下。
导入安全的库

import Security

数据存到钥匙串,需要注意的已经存过这个key的话,这样存不了新值,这样只能加不能刷新已有的

 // 存储数据到钥匙串中
        let value = "这个是要存的数据字符串"
        let key = "MyPassword" //存储数据的键
        let data = value.data(using: .utf8)!

        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: key,
            kSecValueData as String: data,
        ]

        let status = SecItemAdd(query as CFDictionary, nil)
        if status != errSecSuccess {
            print("Error saving to keychain")
        }

下面是刷新已有的钥匙串数据,必须是已有的钥匙串数据,不能作为添加的能力。

        let key = "MyPassword" //存储数据的键
        let value = "这个是要刷新的数据字符串"
     
        let data = value.data(using: .utf8)!
        let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
                                    kSecAttrAccount as String: key]

       
        let attributes: [String: Any] = [
            kSecValueData as String: data
        ]


        let status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
        if status != errSecSuccess {
            print("Failed to update password in keychain")
        }

从钥匙串取数据:

// 从钥匙串中获取数据
        let getQuery: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrAccount as String: key,//上文的那个key
            kSecReturnData as String: kCFBooleanTrue!,
            kSecMatchLimit as String: kSecMatchLimitOne,
        ]

        var dataTypeRef: AnyObject?
        let status2 = SecItemCopyMatching(getQuery as CFDictionary, &dataTypeRef)
        if status2 == errSecSuccess {
            let retrievedData = dataTypeRef as! Data
            let retrievedValue = String(data: retrievedData, encoding: .utf8)
            //retrievedValue 为从钥匙串中取出来的字符串
            print("Retrieved value: \(retrievedValue ?? "Error decoding value")")
        } else {
            print("Error retrieving value from keychain")
        }

你可能感兴趣的:(swift,ios,开发语言)