Reputation: 1021
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:
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
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
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
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
Reputation: 299325
The localized message is in the localizedDescription
property:
error.localizedDescription
Upvotes: 2