URLRequest debugging
For most iOS applications, we need to handle server communication. UIKit provides URLRequest
which manages requests to server. In this post we’ll take a look at how we can extend it to simplify request debugging.
When working with backend, we frequently encounter situations where we’d like to examine data returned from server as response to our requests, so we usually log requests (and replies) to be prepared for when communication doesn’t go according to expectations.
But frequently we want to examine the data independently of the application - for example, it may take couple steps to reach the screen that uses certain endpoint, or we just want to confirm the data is correctly interpretted by our code. We could do that with curl
in Terminal, but that’s complicated due to various factors like OAuth tokens or dynamic headers we need to attach in order for request to succeed.
Or is it? URLRequest
already includes all the data needed, so why can’t we use it to log curl
command we can later paste and use in Terminal? No reason at all 😉
Solution
Declare extension to URLRequest
:
extension URLRequest {
public var curlString: String {
// Logging URL requests in whole may expose sensitive data,
// or open up possibility for getting access to your user data,
// so make sure to disable this feature for production builds!
#if !DEBUG
return ""
#else
var result = "curl -k "
if let method = httpMethod {
result += "-X \(method) \\\n"
}
if let headers = allHTTPHeaderFields {
for (header, value) in headers {
result += "-H \"\(header): \(value)\" \\\n"
}
}
if let body = httpBody, !body.isEmpty, let string = String(data: body, encoding: .utf8), !string.isEmpty {
result += "-d '\(string)' \\\n"
}
if let url = url {
result += url.absoluteString
}
return result
#endif
}
}
Usage
And log it:
let request = ...
print("\(request.curlString)")
And voila! We’re ready for next hard core debugging session - enable logging, navigate to screen with request you want to log and copy the text from Xcode console! 😀
Conclusion
With minimal work we created useful debugging tool! BUT it’s not just our debugging tool, curl
s are super useful to pass on to backend developers so they can easily investigate the issue on their side! Or to simplify the import to Paw. Or…. 😉