Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug network request Swift

Tags:

json

swift

I'm making a http request to an API with JSON in the body of the request. I know for a fact that my Dictionary<String, String> containing the JSON data is correct, still I'm getting a response from the server that my input data is not valid. I'm doing something very similar to this: Swift 2.0 url post request. I even tried the extension suggested there but without success.

how should I debug this? I can't find any way to print my whole request to the console. I want to know what my URLRequest actually contains just before I send the request. Also, I want to know that this hex gibberish is actually the right gibberish I meant it to be, how should I do this?

like image 776
Fr4nc3sc0NL Avatar asked Dec 11 '22 19:12

Fr4nc3sc0NL


1 Answers

Nothing special about that? Just write an extension and print whatever you want

example:

extension Data {
    func toString() -> String? {
        return String(data: self, encoding: .utf8)
    } 
}

extension URLRequest {
    func log() {
        print("\(httpMethod ?? "") \(self)")
        print("BODY \n \(httpBody?.toString())")
        print("HEADERS \n \(allHTTPHeaderFields)")
    }
}

Usage:

request.log()

Sample log:

POST https://httpbin.org/
BODY 
Optional("password=xxx&username=xxx")
HEADERS 
Optional(["Content-Type": "application/x-www-form-urlencoded; charset=utf-8"])
like image 175
vasantpatel Avatar answered Jan 02 '23 07:01

vasantpatel