【发布时间】:2016-10-02 04:04:08
【问题描述】:
我是 iOS 和 Swift 的新手,我正在尝试使用 AlamoFire 3.4.0 发出网络请求。当我的请求成功时,一切正常。但是,如果我的请求失败,服务器将在响应正文中返回 300 或更大的状态代码和一些 JSON,其中包含有关请求失败原因的更多信息。例如,我正在使用的 API 要求对每个请求进行身份验证。如果由于某种原因身份验证失败,我将返回 401,响应正文中的 JSON 将是:
{"developerMessage" : "Request failed because signature was incorrect."}
我发出这个请求的代码如下所示:
let headers = [
"X-Auth-Signature" : signature
]
Alamofire.request(.GET, "https://server.com/get", headers: headers)
.validate()
.responseJSON { response in
switch response.result {
case .Success(let json)
// process JSON response here
case .Failure(let error)
print("Request failed with error: \(error)")
// how can I access the JSON in the response body from here?
}
}
据我了解,对 .validate() 的调用将验证状态代码是 200 - 299,而超出该范围的所有其他内容都将导致 .Failure 情况。假设这是正确的,当我返回 401 时,如何从故障处理程序内部访问响应正文中的 JSON?非常感谢!
【问题讨论】:
-
请在此处查看答案*.com/a/35324741/5093900