在HTTP错误期间以任何方式获取响应主体?

时间:2016-01-29 15:34:55

标签: ios swift httpresponse alamofire http-status-code-403

我正在点击偶尔会抛出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错误的情况下,它似乎没有给我回复响应主体。是否有解决方法或我在这里缺少的东西?

2 个答案:

答案 0 :(得分:75)

我在他们的github页面上问过这个问题,并从cnoon得到答案:

swift 2:

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

迅捷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。

答案 1 :(得分:3)

快速键5在DefaultDataResponse扩展名中轻松获得正文响应:

String(data: data!, encoding: String.Encoding.utf8)
相关问题