在 alamofire 2 中,他们引入了结果类型:
Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseJSON { request, response, result in
switch result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
case .Failure(let data, let error):
print(error)
}
}
error 是 ErrorType 类型,它的唯一成员是 debugDescription,它打印:
Optional(Error Domain=NSURLErrorDomain Code=-1009 "Es besteht anscheinend keine Verbindung zum Internet." UserInfo={NSUnderlyingError=0x135f4e7c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorCodeKey=8, _kCFStreamErrorDomainKey=12}}, NSErrorFailingURLStringKey=myurl, NSErrorFailingURLKey=myurl, _kCFStreamErrorDomainKey=12, _kCFStreamErrorCodeKey=8, NSLocalizedDescription=Es besteht anscheinend keine Verbindung zum Internet.})
如何从错误中获取 NSLocalizedDescription 而不是整个调试消息?
在 alamofire 1 中,错误是 NSError 类型,可以通过以下方式获取错误消息:
error.localizedDescription
然而这在 alamofire 2 中似乎是不可能的。有什么想法吗?
最佳答案
在"Alamofire 2.0 Migration Guide"据称是一种新的结果类型
public enum Result<Value> {
case Success(Value)
case Failure(NSData?, ErrorType)
}
被引入,Alamofire 仍然只生成 NSError 对象。
在"Why and how any ErrorType can always be casted to NSError?"的成员
Apple Stuff 确认 ErrorType
总是可以转换
到一个 NSError
:
... The reason this works is because of "compiler magic." The compiler automatically emits the code necessary to translate between any ErrorType and NSError.
所以这会快速编译并打印出预期的结果 测试(例如“无法连接到服务器。”):
switch result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
case .Failure(let data, let error):
print((error as NSError).localizedDescription)
}
关于swift - Alamofire 2,如何获取 NSError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32667948/