【问题标题】:Unexpected Crash when Using Swift Keychain Wrapper使用 Swift Keychain Wrapper 时意外崩溃
【发布时间】:2018-06-12 02:18:23
【问题描述】:

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

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

线程 1:致命错误:在展开可选值时意外发现 nil

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

有问题的代码是:(致命错误发生在“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!)
    }
}

【问题讨论】:

标签: ios swift keychain


【解决方案1】:

基本错误——替换:

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

到:

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

有效。

Duh,"" 仍然有字符串形式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多