Todd Hopkinson
Todd Hopkinson

Reputation: 6903

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

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?

Upvotes: 34

Views: 38714

Answers (3)

spnkr
spnkr

Reputation: 1392

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

Upvotes: 3

7Cornelio
7Cornelio

Reputation: 7

Old question, but anyway...

You don't need to get to the operation object, you can easily do something like:

NSData * data = [NSJSONSerialization dataWithJSONObject:JSON options:0 error:nil]];

With the JSON id that the callback receives.

Upvotes: -4

mattt
mattt

Reputation: 19544

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.

Upvotes: 52

Related Questions