我是iOS和Swift的新手,我正在尝试使用AlamoFire3.4.0来做一个web请求。当我的请求成功时,一切都很好。但是,如果我的请求失败,服务器将返回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?
}
}
我的理解是,对
case .Failure(let error)
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
应该能奏效