How to get the response data out of the NSHTTPURLResponse in the callback of AFJSONRequestOperation?

33,291

Solution 1

NSHTTPURLResponse only contains HTTP header information; no body data. So no, this would be impossible. If you have any control over this code, have the block or method pass the operation itself and get responseData or responseJSON.

Solution 2

In the callback from responseJSON you can get the body from a DataResponse<Any> object using response.result.value or String(data:response.data!, encoding: .utf8).

You can't get it from response.response, which is a NSHTTPURLResponse object. This only has header info.

Alamofire.request(URL(string: "https://foo.com")!).validate(statusCode: 200..<300).responseJSON() { response in
    let body = response.result.value
}

If the http response doesn't validate the above doesn't work. but this does:

Alamofire.request(URL(string: "https://foo.com")!).validate(statusCode: 200..<300).responseJSON() { response in
    let body = String(data:response.data!, encoding: .utf8)
}
Share:
33,291
Todd Hopkinson
Author by

Todd Hopkinson

Creative Technologist @LavaMonsterLabs • Previously: @nike on @nikefuel, @garmin, @apriva • Husband. Father of six. (Long version) Todd Hopkinson is a Creative Technologist &amp; Senior iOS Developer. He was Nike's iOS Team Lead on FuelBand for iOS. His experience includes working at Nike alongside teams at Apple, Synapse, RG/A, Nike, AKQA, and other talented groups. He has worked for clients developing fitness, payment, wallet, hotel, shopping, travel, pharmaceutical, and other applications. His experience includes direct collaborations with Nike, Apple, Synapse, R/GA, and many more talented groups. He spent nearly a decade developing software at aerospace and defense company General Dynamics. He also published several independent iOS apps to the AppStore.

Updated on June 28, 2020

Comments

  • Todd Hopkinson
    Todd Hopkinson about 4 years

    I have a situation where I need to access the raw response data for an AFJSONRequestOperation, from within the callback block which includes only NSHTTPURLResponse. I am able to get the statusCode from the NSHTTPURLResponse, but don't see any way to get to the raw data. Is there a good way that anyone knows of to access this from the failure callback block of this operation?