Topics

#56: ResponseDetective 🔍

Topics

ResponseDetective is a new debugging library from Adrian Kashivskyy and the team at Netguru for "intercepting" HTTP activity and logging it. You can configure different sets of Interceptor classes, depending on what kinds of data you'd like to see. Let's set it up:

The first thing we'll need to do is register some request and response Interceptors. ResponseDetective comes with quite a few Interceptors out of the box, and you can of course create your own. Here we'll log all the headers of all requests and responses, as well as the content of any JSON requests.

We start with the default session config, and insert the InterceptingProtocol at the front of it's protocol classes.

Finally, we create a session with our config and kick off a new task to an example API endpoint.

InterceptingProtocol.registerRequestInterceptor(HeadersInterceptor())
InterceptingProtocol.registerResponseInterceptor(HeadersInterceptor())
InterceptingProtocol.registerErrorInterceptor(HeadersInterceptor())

InterceptingProtocol.registerResponseInterceptor(JSONInterceptor())

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()

configuration.protocolClasses = map(configuration.protocolClasses, {
  (var protocolClasses) in
    protocolClasses.insert(InterceptingProtocol.self, atIndex: 0)
    return protocolClasses
}) ?? [InterceptingProtocol.self]

let session = NSURLSession(configuration: configuration)

session.dataTaskWithRequest(
    NSURLRequest(URL: NSURL(string: "http://httpbin.org/get")!)
).resume()

Now, if we look at our console, we can see that all the HTTP activity has been logged:

GET http://httpbin.org/get

200 no error
Content-Length: 304
Server: nginx
Content-Type: application/json
Access-Control-Allow-Origin: *
Date: Mon, 10 Aug 2015 04:11:45 GMT
Access-Control-Allow-Credentials: true
Connection: keep-alive
{
  "args" : {

  },
  "headers" : {
    "User-Agent" : "056-responsedetective\/1 CFNetwork\/711.4.6 Darwin\/14.4.0",
    "Accept-Encoding" : "gzip, deflate",
    "Host" : "httpbin.org",
    "Accept-Language" : "en-us",
    "Accept" : "*\/*"
  },
  "origin" : "76.102.27.127",
  "url" : "http:\/\/httpbin.org\/get"
}

More info about ResponseDetective can be found at git.io/responsedetective