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:


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

    1. Hi Sana,

      Try this solution,
      It is working fine for me in Swift 3.0.1 and Xcode version 8.2.1.

      // Assign your url here
      var urlstring:String = "YOUR_URL_HERE"

      urlstring = urlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!

      let manager : AFHTTPRequestOperationManager = AFHTTPRequestOperationManager()

      manager.responseSerializer.acceptableContentTypes = Set(["application/json", "text/json", "text/javascript", "text/html"])

      manager.get( "\(urlstring)",
      parameters: nil,
      success: { (operation: AFHTTPRequestOperation?,responseObject: Any?) in
      // Check the output is Array format or Dictionary
      let jsonObjects=responseObject as! NSArray
      // var dataDict: NSDictionary?
      let value = jsonObjects[0] as AnyObject

      failure: { (operation: AFHTTPRequestOperation?,error: Error) in
      print("Error: " + error.localizedDescription)

Leave a Reply to Sana Cancel 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="">