Roduck Nickes
Roduck Nickes

Reputation: 1021

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?

Upvotes: 2

Views: 2751

Answers (4)

vadian
vadian

Reputation: 285079

Just write

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

As the error is always non-nil if the user is nil, you can safely unwrap it.

Upvotes: 2

keshav vishwkarma
keshav vishwkarma

Reputation: 1852

You can also try below code using the optional binding and nil coalescing operator

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

Upvotes: 1

rmaddy
rmaddy

Reputation: 318794

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.

Upvotes: 4

Rob Napier
Rob Napier

Reputation: 299325

The localized message is in the localizedDescription property:

error.localizedDescription

Upvotes: 2

Related Questions