简体   繁体   English

如何从NSError.description中获取[错误] :?

[英]How can I get the [Error]: from NSError.description?

I am trying to create a UIAlertView that displays only the error of NSError.description . 我试图创建仅显示NSError.description错误的UIAlertView

For example: 例如:

var alert = UIAlertView(title: "Oops!", message: error.description, delegate: self, cancelButtonTitle: "OK")
alert.show()

Say the error.description outputs: 说出error.description输出:

2015-02-01 02:26:43.227 UserLogin[249:13655] [Error]: missing username (Code: 200, Version: 1.6.2)

How can I just get the [Error]: missing username in a String ? 我怎样才能得到[Error]: missing username String [Error]: missing username I am new to app development and I simply want my error messages to make sense to the user and to be simple. 我是应用程序开发的新手,我只想让我的错误消息对用户有意义且简单。

If this does not make sense, I am using Parse and I am working on a registration form. 如果这没有意义,则说明我正在使用Parse,并且正在处理注册表。 If the error occurs such as "missing username" , "username taken" , etc. I just wanted to find a way to get a simple error popup to say "username taken" . 如果发生错误,例如“缺少用户名”“采用用户名”等,我只是想找到一种方法来获取简单的错误弹出窗口,说“采用用户名”

You can use the localizedDescription property of NSError . 您可以使用NSErrorlocalizedDescription属性。

Instead of error.description use error.localizedDescription 代替error.description使用error.localizedDescription

var alert = UIAlertView(title: "Oops!", message: error.localizedDescription, delegate: self, cancelButtonTitle: "OK")
alert.show()

Note: 注意:

UIAlertView is deprecated in iOS 8, use UIAlertController instead. UIAlertView在iOS 8中已弃用,请改用UIAlertController

Try using this: 尝试使用此:

if let dic  = error?.userInfo {
   let errorString = dic[NSUnderlyingErrorKey]?.localizedDescription
   var alert = UIAlertView(title: "Oops!", message:errorString, delegate: self, cancelButtonTitle: "OK")
   alert.show()
}

Before you go in that direction, you should think very, very hard whether the NSError that you received is meant to be seen by a user. 在朝这个方向发展之前,您应该非常非常认真地思考是否收到的NSError是否应该被用户看到。 Many NSErrors are meant to be examined by a programmer only. 许多NSError仅应由程序员检查。 In this case, "missing username" seems a strong indication that you, the programmer, made a mistake by sending a request without a username and shouldn't have done that in the first place. 在这种情况下,“缺少用户名”似乎有力地表明,程序员您通过发送不带用户名的请求而犯了一个错误,因此一开始就不应该这样做。 So showing an error alert may be the totally wrong solution. 因此,显示错误警报可能是完全错误的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM