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

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

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


Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.

Topics:
ios ,swift ,alamofire ,networking

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}