快速创建NSError对象

2020/12/17 01:32 · ios ·  · 0评论

我正在尝试创建一个错误对象以显示给用户。

let userInfo: [NSObject : AnyObject] = 
    [
    "NSLocalizedDescriptionKey" :  NSLocalizedString("Unauthorized", comment: ""),
    "NSLocalizedFailureReasonErrorKey" : NSLocalizedString("Unauthorized", comment: "")
    ]
let err = NSError(domain: "ShiploopHttpResponseErrorDomain", code: httpResponse.statusCode, userInfo: userInfo)
print("Error in Post: \(err.localizedDescription)")

不幸的是输出是:

Error in Post: The operation couldn’t be completed.(ShiploopHttpResponseErrorDomain error 401.) 

我希望能够向用户表明他应该激活他的帐户。有任何想法吗??

看起来像您想要的(请参阅字典键):

迅捷2

let userInfo: [NSObject : AnyObject] =
[
    NSLocalizedDescriptionKey :  NSLocalizedString("Unauthorized", value: "Please activate your account", comment: ""),
    NSLocalizedFailureReasonErrorKey : NSLocalizedString("Unauthorized", value: "Account not activated", comment: "")
]

迅捷3

let userInfo: [AnyHashable : Any] =
            [
                NSLocalizedDescriptionKey :  NSLocalizedString("Unauthorized", value: "Please activate your account", comment: "") ,
                NSLocalizedFailureReasonErrorKey : NSLocalizedString("Unauthorized", value: "Account not activated", comment: "")
        ]

然后像这样在swift 2或3中创建错误对象:

let err = NSError(domain: "ShiploopHttpResponseErrorDomain", code: 401, userInfo: userInfo)
println("Error in Post: \(err.localizedDescription)")

NSLocalizedDescriptionKey和NSLocalizedFailureReasonErrorKey是全局String变量,以及userInfo字典中的键。这些值与您指定的值略有不同:

println(NSLocalizedDescriptionKey) //prints "NSLocalizedDescription"
println(NSLocalizedFailureReasonErrorKey) //prints "NSLocalizedFailureReason"

我发现通过右键单击该类(在本例中为NSError)并在xcode中选择“跳转到定义”来查看文档是一种很好的做法。各种问题都可以通过这种方式回答。:)

在Swift 3中创建一个非常简单的错误:

let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Object does not exist"])

创建错误很简单,如以下行所示:

let error = NSError(domain: "com.example.error", code: 0, userInfo: [NSLocalizedDescriptionKey: "message"])

如果您需要其他堆栈跟踪信息,请使用以下方法:

func error(_ message: String, code: Int = 0, domain: String = "com.example.error", function: String = #function, file: String = #file, line: Int = #line) -> NSError {

    let functionKey = "\(domain).function"
    let fileKey = "\(domain).file"
    let lineKey = "\(domain).line"

    let error = NSError(domain: domain, code: code, userInfo: [
        NSLocalizedDescriptionKey: message,
        functionKey: function,
        fileKey: file,
        lineKey: line
    ])

    // Crashlytics.sharedInstance().recordError(error)

    return error
}

用法:

let localizedErrorMessage: String = NSLocalizedString("Unauthorized", comment: "Account not activated")
let error = error(localizedErrorMessage)
本文地址:http://ios.askforanswer.com/kuaisuchuangjiannserrorduixiang.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!