将 NSError 显示为消息

Show NSError as a message

如何将错误显示为正常消息:

我有登录功能:

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 向用户显示:

但是我怎样才能只显示消息:

Invalid username/password.

我尝试使用 error.message,但这不是命令,error.description 也不起作用。有什么建议吗?

本地化消息在 localizedDescription property:

error.localizedDescription

只需使用 localizedDescription.

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

或者从错误的 userInfo 字典中获取 "error" 键的值。

随便写

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

如果用户是 nil,错误总是非 nil,您可以安全地解包它。

您也可以使用 optional bindingnil coalescing operator

尝试下面的代码
let alert = UIAlertController(title: "Error", message: "\( error?.localizedDescription ?? " unknown error " )", preferredStyle: .Alert)