0

I recently got introduced to Swift Keychain Wrapper, a very useful tool to do simple saving and retrieving user login information. I created two buttons: one for saving the username and password, and the other for retrieving and filling the username and password.

However, in the case where if the first thing the user did was to click the "retrieve and fill" button, the App crashes with:

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

I have an "if" function to alert the user that if there is nothing saved they should be alerted, but the program just skips it. I am in need of some help.

The piece of code with the issue is: (The fatal error occurs in the "else" part)

//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!)
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Andrew Qin
  • 67
  • 2
  • 11
  • 1
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – mfaani Jun 12 '18 at 02:32

1 Answers1

0

Basic mistake -- replacing:

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

to:

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

works.

Duh, "" still has something as a string

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Andrew Qin
  • 67
  • 2
  • 11