有什么方法可以在 HTTP 错误期间获取响应正文?

Any way to get the response body during HTTP errors?

我遇到了一个偶尔会抛出 HTTP 403 错误的 API,并且响应正文可以 json 的形式提供一些额外的信息,但是为了我的生活,我似乎无法从 Alamofire 响应对象中取回信息。如果我通过 chrome 点击 API,我会在开发者工具中看到信息。这是我的代码:

Alamofire.request(mutableURLRequest).validate().responseJSON() {
    (response) in
    switch response.result {
        case .Success(let data):
            if let jsonResult = data as? NSDictionary {
                completion(jsonResult, error: nil)
            } else if let jsonArray = data as? NSArray {
                let jsonResult = ["array" : jsonArray]
                completion(jsonResult, error: nil)
            }
        case .Failure(let error):
            //error tells me 403
            //response.result.data can't be cast to NSDictionary or NSArray like
            //the successful cases, how do I get the response body?
    }

我已经查询了几乎所有附加到响应的对象,但在 HTTP 错误的情况下它似乎没有给我返回响应正文。是否有解决方法或我在这里遗漏的东西?

我在他们的 github 页面上问了这个问题,得到了 cnoon 的回答:

swift 2:

if let data = response.data {
    let json = String(data: data, encoding: NSUTF8StringEncoding)
    print("Failure Response: \(json)")
}

swift 3:

if let data = response.data {
    let json = String(data: data, encoding: String.Encoding.utf8)
    print("Failure Response: \(json)")
}

https://github.com/Alamofire/Alamofire/issues/1059

我只是省略了编码部分,通过这样做,即使在出现错误的情况下,您也可以获得响应json。

Swift 5 在 DefaultDataResponse 扩展中轻松获得 body 响应:

String(data: data!, encoding: String.Encoding.utf8)