Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

ios - Any way to get the response body during HTTP errors?

I'm hitting an API that will occasionally throw a HTTP 403 error, and the response body can give some extra information in the form of json, however for the life of me I can't seem to get the information back out from the Alamofire response objects. I see the information in developer tools if I hit the API via chrome. Here's my code:

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?
    }

I've queried pretty much every object attached to the response, but it doesn't seem to give me the response body back in the case of HTTP errors. Is there a work-around or something I'm missing here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I asked this question on their github page and got an answer from 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

I just left out the encoding part, by doing this you are able to get the response json even in the case of errors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...