Sending post data from swift datatask to PHP fails due to data corruption. How to fix this?

44 Views Asked by At

I send a POST request in my Swift app to my server, but the data received by the server is different from what I intended to send to the server.

The data I try to send is:

let parameters = PostData(
  previousVisit : previousVisit,
  lang : lang,
  object : object,
  enrolledSince : since
)

Which comes down in practice to:

PostData(previousVisit: "2024-03-20T10:33:48", lang: "NL", object: "{\"Location\":[\"19\"],\"Event\":[]}", enrolledSince: "{}")

But the server receives:

array(1) {
  ["{"lang":"NL","object":"{\"Location\":"]=>
  array(1) {
    ["\"19\""]=>
    string(0) ""
  }
}

This is really strange. It seems that a part of the data is interpreted as key and a part as value and some data is lost.

This is the code I use to send it:

let url = URL(string: "MyPHPServer.com/script.php")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try! JSONEncoder().encode(parameters)
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

etc.

Where did I fail?

I expect the same result on the server as in Swift. I tried to find out why it fails, by I couldn't find it.

1

There are 1 best solutions below

1
Frank Jansons On

Okay, I don't understand it, but I found a working solution.

let queryItems = [
  URLQueryItem(name: "previousVisit", value: previousVisit),
  URLQueryItem(name: "lang", value: lang),
  URLQueryItem(name: "object", value: object),
  URLQueryItem(name: "enrolledSince", value: since)
]

// Create a URLComponents object using blank url
var urlComponents = URLComponents(string: "")
        
// Assign the query items to the object
urlComponents?.queryItems = queryItems
        
// Fetch the formatted string from the URLComponents object
let request_body = urlComponents!.query!
    
request.setValue(
 "application/x-www-form-urlencoded",
 forHTTPHeaderField: "Content-Type"
)
 
request.httpMethod = "POST"
                       
request.httpBody = Data(request_body.utf8)

This worked in the session.DataTask for me.