如何将错误显示为正常消息:
我有一个登录功能:
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)
}
}
}
UIAlertController向用户显示:
但是我怎么才能将消息显示为:
用户名/密码无效。
我尝试使用error.message,但那不是命令,而且error.description也不起作用..有什么建议吗?
答案 0 :(得分:1)
本地化消息位于localizedDescription
property:
error.localizedDescription
答案 1 :(得分:1)
只需写下
let alert = UIAlertController(title: "Error", message: "\(error!.localizedDescription)", preferredStyle: .Alert)
如果用户是nil
,则错误始终为非nil
,您可以安全地将其解包。
答案 2 :(得分:0)
您还可以使用optional binding
和nil coalescing operator
let alert = UIAlertController(title: "Error", message: "\( error?.localizedDescription ?? " unknown error " )", preferredStyle: .Alert)