我最近接触到了 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/