0

I want to print my request.httpBody sent.

In backend they say that they have not received , so I want to print and see in my console what is being sent.

when I print(request.httpBody) I get bytes

my code

    let param = "AppId=\(Config.AppID)&uuid=\(Config.uuid)&file=\("file")&id=\(ID)"

    var requestBodyData = (dataString as NSString).data(using: String.Encoding.utf8.rawValue)
    requestBodyData?.append(param.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!)

    do {
    request.httpBody = requestBodyData
    } catch let error {
        print(error.localizedDescription)
    }

 //How to print this request.httpBody ? 
  // Make an asynchronous call so as not to hold up other processes.
    URLSession.shared.dataTask(with: request) { data, response, error in

        // get main queue to communicate back to user
        DispatchQueue.main.async(execute: {

            if error == nil {

                do {
                    // json containes $returnArray from php
                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary


               }
                )}
swift_USer
  • 159
  • 3
  • 15
  • 1
    I'd suggest you check the `response` (notably, what is its `statusCode`) and `error` (generally it will include informative information). In terms what could be going wrong. In terms of possible sources of problems include (a) that this `param` string might include characters that need to be percent escaped; and (b) that you didn't set `httpMethod` to `"POST"`. – Rob Dec 12 '17 at 09:36
  • 1
    You have the body content as a `String` already.... `print(dataString)` – Scriptable Dec 12 '17 at 09:37
  • @Rob My httpMethod is of type POST only, which I did not displayed in query here. How do you want me to pass param string ? – swift_USer Dec 12 '17 at 09:42
  • You'll want to percent escape the values in this query. See the `String` and `Dictionary` extensions in the latter half of [this answer](https://stackoverflow.com/a/27724627/1271826), which show how to pass a dictionary (e.g. `["AppId": "..."]` and have it build a proper, percent escaped string. Now that question was about how to build URLs (where we'd now use `URLComponents` to do all of this for you), but when building the body of POST requests, like here, the extension that uses `addingPercentEncodingForURLQueryValue` will work great. – Rob Dec 13 '17 at 00:07
  • By the way, if you want to see exactly how the request was sent (and exactly what response you got), tools like [Charles](http://charlesproxy.com) and [WireShark](http://wireshark.org) are great. You usually only resort to tools like these if you’re worried about what all the headers and body look like. They’re overkill for a situation like this, but they’re really powerful diagnostic tools. – Rob Dec 13 '17 at 02:12

0 Answers0