1

How do I attach multiple data with a POST request in Swift. As attached screen shot from Postman it is working fine when select the x-www-form-urlencoded option How do I attach 5 data with the body like 'x-www-form-urlencoded' option?

Here the code:

var request = URLRequest(url: urlString)
        request.httpMethod = "POST"
        request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
        
        var urlComponents = URLComponents()
        urlComponents.queryItems = [
            URLQueryItem(name: “***”, value: “***”),
            URLQueryItem(name: "***", value: "***"),
            URLQueryItem(name: "***", value: "***"),
            URLQueryItem(name: "***", value: "***"),
            URLQueryItem(name: "***", value: "***"),
        ]
        request.httpBody = urlComponents.percentEncodedQuery?.data(using: String.Encoding.utf8)
        
        let loadDataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let _ =  error{
                completion(false,error)
            }
            else if let response = response as? HTTPURLResponse{
                if response.statusCode != 200{
                    completion(false,error)
                }
                else{
                    do{
                        if let parsedData = try? JSONSerialization.jsonObject(with: data!, options: []){
                            let ff = parsedData as? Dictionary<String,Any>
                            print(ff)
                        }
                    }
                }
                
            }
        }//let loadDataTask
        loadDataTask.resume()
    }

enter image description here

2
  • String data only
    – Vineesh TP
    Commented May 1, 2018 at 11:47
  • **Simplest solution: ** Click on Code in postman (attached screen). Select Swift in the modal appears after clicking Code. You will get the code you need, remove the unnecessary postman parameters
    – Satish
    Commented May 1, 2018 at 12:12

2 Answers 2

5

One easy way to create the http body is to use URLComponents like this:

var request = URLRequest(url: yourUrl)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")

var urlComponents = URLComponents()
urlComponents.queryItems = [
    URLQueryItem(name: "your_first_parameter", value: "someValue"),
    URLQueryItem(name: "your_second_parameter", value: "someValue"),
    URLQueryItem(name: "your_third_parameter", value: "someValue")
]
request.httpBody = urlComponents.percentEncodedQuery?.data(using: .utf8)
2
  • I have updated the code. it is not working. I got response code 400.
    – Vineesh TP
    Commented May 1, 2018 at 12:05
  • Did you set the query items correctly? Because otherwise there is nothing different to your accepted solution. Except this solution is more robust regarding the query encoding. Commented May 1, 2018 at 13:23
2

SWIFT 4:

let url = URL(string: “url”);
var urlRequest = URLRequest(url: url!)
urlRequest.setValue("application/x-www-form-urlencoded",forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "POST"
let postString = “paramerter1=value1&parameter2=value2”
urlRequest.httpBody = postString.data(using: .utf8)
1
  • This answer doesn't encode the data properly as far as I can see
    – boxed
    Commented Oct 28, 2023 at 17:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.