iosswiftnserror

Show NSError as a message


How can I show a error as a normal message:

I have a signin function:

func signIn() {
        PFUser.logInWithUsernameInBackground(self.usernameTextField.text!, password: self.passwordTextField.text!) {
            (user: PFUser?, error: NSError?) -> Void in
            if user != nil {
                // Do stuff after successful login.
                print("User successfully logged in: \(user)")
                self.performSegueWithIdentifier("loginSegue", sender: nil)
            } else {
                // The login failed. Check error to see why.
                print("Server reported an error: \(error)")

                // create the alert
                let alert = UIAlertController(title: "Error", message: "\(error)", preferredStyle: UIAlertControllerStyle.Alert)

                // add an action (button)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                // show the alert
                self.presentViewController(alert, animated: true, completion: nil)
            }
        }
    }

And the UIAlertController shows this to the user:

enter image description here

But how can I only show message as:

Invalid username/password.

I tried using error.message, but thats not a command, and error.description does not work either.. Any suggestions?


Solution

  • Just use the localizedDescription.

    let alert = UIAlertController(title: "Error", message: "\(error.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert)
    

    Or get the value for the "error" key from the error's userInfo dictionary.