or “How to POST a form in Swift using URLSession”

These examples will be using httpbin.org to test our request.

let url = URL(string: "https://httpbin.org/post")

Create a URLRequest object using the URL

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

Create a list of key-values to be sent

let queryItems = [
            URLQueryItem(name: "x", value: 123),
            URLQueryItem(name: "y", value: "hello"),
            URLQueryItem(name: "z", value: "world"),
        ]

Construct the body of the POST request

The URLComponents class can be used to construct the body of the HTTP POST request. This is generally used to construct the query params for URLs for HTTP GET requests.

// 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!

Set the body of the request variable

request.httpBody = Data(request_body.utf8)

Make the request using URLSession

URLSession.shared.dataTask(with: request) {(data, response, error) in
    // Decode response from the data variable using JSONDecoder
}