从Keychain中检索帐户名称

时间:2017-06-26 07:02:19

标签: swift3 xcode8 ios10

我想在钥匙串中保存并检索密码和userAccount。我在stackoverflow中找到了一个解决方案,我在那里使用代码。 Save and Load from KeyChain | Swift。但是此代码仅保存并加载密码而不是accountName。我想我想出了如何保存accountName,但我需要弄清楚如何加载密码和密码。这是为您节省一些时间进入该链接的代码。

var userAccount = "AuthenticatedUser"
let accessGroup = "SecurityService"

// Mark: User defined keys for new entry
// Note: add new keys for new secure item and use them in load and save methods
let accountKey = "KeyForAccount"
let passwordKey = "KeyForPassword"

private class func save(service: String, data: String) {
        let dataFromString: NSData = data.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: false)! as NSData

        //Instantiate a new default keychain query
        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue as NSCopying, kSecAttrAccountValue as NSCopying, kSecValueDataValue as NSCopying])

        //Add new keychain item
        let status = SecItemAdd(keychainQuery as CFDictionary, nil)
        if status != errSecSuccess {  //Always check status
            print("Write failed. Attempting update.")
            //updatePassword(token: data)
        }
    }
 private class func load(service: String) -> String? {
        //Instantiate a new default keychain query
        //Tell the query to return a result
        //Limit our results to one item
        let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue as NSCopying, kSecAttrAccountValue as NSCopying, kSecReturnDataValue as NSCopying, kSecMatchLimitValue as NSCopying])

        var dataTypeRef: AnyObject?

        //Search for the keychain items
        let status : OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
        var contentsOfKeychain: String? = nil

        if status == errSecSuccess {
            if let retrieveData = dataTypeRef as? Data {
                contentsOfKeychain = String(data: retrieveData as Data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
            }
        } else {
            print("Nothing was retrieved from the keychain. Status code \(status)")
        }
            print(contentsOfKeychain ?? "none found")
            return contentsOfKeychain   
    }

完整代码在链接中。谢谢大家。

1 个答案:

答案 0 :(得分:0)

  

但此代码仅保存并加载密码而不是accountName。

您显示的代码不会保存或加载密码或帐户名称。

你有两个功能,一个用于保存键/值对,一个用于加载键值。这就是你如何调用这两个函数来决定保存/加载的内容。

在代码的某处,您拨打save来保存密码,您需要拨打save(使用其他密钥)来保存帐户名称。同样适用于load。您的代码确定了要使用的两个键(accountKey& passwordKey)。

HTH