Pass Form-Data in POST request


Hi, as in the topic, I’m having issue with passing Form-Data in Swift.
I have solution in Javascript (works as intended):

function sendRequest(type, url, data, callback, onFail) {
var request = new XMLHttpRequest();
var response;

  request.open(type, url, true);
  request.send(data);

  request.onreadystatechange = function() {
    if (request.readyState==4 && request.status==200) {
      callback(request.responseText)
    }
    else if (request.status!=200){
      onFail()
    }
  }

  request.timeout = 5000;
  request.ontimeout = function (e) {
    onFail()
  };
}

sendRequest('POST',"https://myurl.com/something.aspx", formData,(response)=>console.log(response),(error)=>console.log(error));

Where in formData I pass as an argument is a plain text of Form-Data.

Here’s one of my many attempts in Swift:

var request = URLRequest(url: url)
request.httpMethod = "Post"
request.httpBody = formData.data(using: String.Encoding.utf8)
NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main){
    (response, data, error) in
    print(String(data: data!, encoding: String.Encoding.utf8))
 }

But doesn’t work. I found some other solutions, like using Alamofire, or some share API in stackoverflow, but all of those expect parameters to be sent in [String : Any] type - which is an another issue.

@maltaz Do you still have issues with this?

This topic was automatically closed after 166 days. New replies are no longer allowed.