ios - 使用 Swift 钥匙串(keychain)包装器时发生意外崩溃

标签 ios swift keychain

我最近接触到了 Swift Keychain Wrapper,这是一个非常有用的工具,可以简单地保存和检索用户登录信息。我创建了两个按钮:一个用于保存用户名和密码,另一个用于检索和填写用户名和密码。

但是,如果用户所做的第一件事是单击“检索并填充”按钮,则应用程序会崩溃:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

我有一个“if”函数来提醒用户,如果没有保存任何内容,他们应该收到警报,但程序只是跳过它。我需要一些帮助。

有问题的代码是:( fatal error 发生在“else”部分)

//Actions for retrieving username and password 
@IBAction func retrieveUsernameButtonTapped(_ sender: UIButton) {

    //Alert user if there is nothing to be retrieved
    if  KeychainWrapper.standard.string(forKey: "userName") == "" || KeychainWrapper.standard.string(forKey: "userPassword") == "" {
        let alertController = UIAlertController(title: "Error", message: "You don't have any saved User ID and Password!", preferredStyle: .alert)

        let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
        alertController.addAction(defaultAction)

        self.present(alertController, animated: true, completion: nil)

    }

    //Else proceed to filling in
    else {
    let retrievedUsername: String? = KeychainWrapper.standard.string(forKey: "userName")
    print("Retrieved username is: \(retrievedUsername!)")
    emailTextField.text = (retrievedUsername!)

    let retrievedPassword: String? = KeychainWrapper.standard.string(forKey: "userPassword")
    print("Retrieved password is: \(retrievedPassword!)")
    passwordTextField.text = (retrievedPassword!)
    }
}

最佳答案

基本错误——替换:

KeychainWrapper.standard.string(forKey: "userName") == ""

至:

KeychainWrapper.standard.string(forKey: "userName") == nil

有效。

呃,"" 仍然有一些字符串

关于ios - 使用 Swift 钥匙串(keychain)包装器时发生意外崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808391/

相关文章:

iphone - UIImage 不是编译时常量,Xcode 4

swift - WatchKit 和地理定位

ios - 禁用和重新启用 Touch ID 时出现钥匙串(keychain)错误 -25300 (errSecItemNotFound)

macos - 使用 Swift 中的 FourCharCode/SecItemAtr 常量

ios - 快速单击按钮时更改 tableView 文本标签

objective-c - 如何更正 "Undefined symbols for architecture i386: "_main"链接问题?

ios - 在范围内找不到类型 'GADRequestError'

ios - 组合字段登录表单 Swift

ios - 适用于 iOS 版本 3 的 Google 地方信息

ios - swift playground/deinit{} 中的内存泄漏未被一致调用