Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Five Minute Swift: Debugging Alamofire Requests

DZone's Guide to

Five Minute Swift: Debugging Alamofire Requests

Learn how to use the power of extensions to see what how your HTTP requests are formed with Alamofire.

· Mobile Zone ·
Free Resource

When REST API calls go wrong, it can be really frustrating to work out where the problem is. Are you missing a header? Or have you sent something incorrect in your request?

There's no shortage of debugging methods for this. There are traditional approaches like using Wireshark to debug all requests and responses, or by installing Charles as an HTTP Monitor on your machine. More recently, there have been some in-app debugging solutions like ResponseDetective which intercepts all calls made by the URLSession. Dotzu gives you a view into networking info, among other logs, so that you can view all calls made by your app.

However, there are times that you just need a really simple solution, without adding yet another framework to your app. If you're already using Alamofire, by leveraging the power of extensions, you'll be able to easy view outgoing requests. 

First, you'll need to define an extension to the Request class as follows:

extension Request {
    public func debugLog() -> Self {
        #if DEBUG
            debugPrint("=======================================")
            debugPrint(self)
            debugPrint("=======================================")
        #endif
        return self
    }
}


This extension will only run as you are debugging the application and prints out the entire Request to the console. 

To use the extension, just use debugLog() after defining your request, like so: 

  Alamofire.request(url).debugLog()
            .responseJSON( completionHandler: { response in
   })


Topics:
ios ,swift ,alamofire ,networking

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}