How to send POST request with parameters in Swift?

Posted by Wei on May 2, 2017

Question

I would like to send a POST request to an API with two parameters. How to start with it?

The API is https://www.google.com/ The parameters are

id = 1234
name = wei

Answer

Below is the example for Swift 3, you can follow with that.

var request = URLRequest(url: URL(string: "https://www.google.com/")!)
request.httpMethod = "POST"
let postString = "id=1234&name=wei"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("error=\(error)")
        return
    }

    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
        print("statusCode should be 200, but is \(httpStatus.statusCode)")
        print("response = \(response)")
    }

    let responseString = String(data: data, encoding: .utf8)
    print("responseString = \(responseString)")
}
task.resume()

Reference


This is the end of post