iOS Swift and AFNetworking: Get response data and status code in case of failure

If you're using the AFNetworking library to perform HTTP queries in an iOS or OS X application, either with Objective-C or Swift, there's no simple way to get the response content in case of failure.

Let's asume the following POST query that send and receive JSON:

We'll now talk about the failure listener, and how to get the response status code and then the data.

Get the status code

The NSURLSessionDataTask object as a response attribute which is a NSHTTPURLResponse object. The status code, which is stored in the statusCode attribute, can simply be accessible this way:

Get the response content

Getting the response content is a little bit more complicated: we have to create our own response serializer. In this case, we’ll override the responseObjectForResponse method of the AFJSONResponseSerializer.

The following implementation simply add the result data in the userInfo of the error object which is accessible in the failure closure:

Then, you’ve to change the response serializer you want to use with your AFNetworking manager:

Based on that we can access to the response content using the error’s userInfo:

facebooktwittergoogle_plusredditpinterestlinkedinmail

One thought on “iOS Swift and AFNetworking: Get response data and status code in case of failure”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">