【问题标题】:Show NSError as a message将 NSError 显示为消息
【发布时间】:2016-04-11 16:06:25
【问题描述】:

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

我有一个登录功能:

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 也不起作用。有什么建议吗?

【问题讨论】:

  • 在这种情况下只显示localisedDescription ....
  • 我还没有阅读答案...我阅读了问题。

标签: ios swift nserror


【解决方案1】:

只需使用localizedDescription

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

或者从错误的userInfo 字典中获取“错误”键的值。

【讨论】:

  • 我如何摆脱可选的?我现在收到这条消息:Optional("Invalid username/password.")
  • 尝试error!.localizeDescription 但这很危险,因为如果errornil,您的应用将会崩溃。
  • 我确实使用过,但仍然在错误消息中看到“可选”文本。但如果它很危险,我还有什么其他选择?
  • 我不了解 Swift,所以我不知道如何处理所有那些疯狂的可选废话(我认为 Swift 应该更容易 - 哈!)。
  • 在这种情况下,最好的可能是可选绑定和 nil 强制的组合,例如error?.localizedDescription ?? "Unknown error".
【解决方案2】:

本地化消息在localizedDescription property:

error.localizedDescription

【讨论】:

    【解决方案3】:

    随便写

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

    由于错误总是非nil,如果用户是nil,你可以安全地解包。

    【讨论】:

      【解决方案4】:

      您也可以使用optional bindingnil coalescing operator 尝试以下代码

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

      【讨论】:

        猜你喜欢
        • 2013-06-23
        • 2016-09-17
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多