perform a network request in swift

Performing a network request in Swift involves using the URLSession API. URLSession provides a set of classes and methods to connect to an HTTP or HTTPS server and exchange data with it. Here's an example of how to perform a basic HTTP GET request:

main.swift
if let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") {
    URLSession.shared.dataTask(with: url) { data, response, error in
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error.localizedDescription)
            }
        }
    }.resume()
}
416 chars
13 lines

In this example, we are creating a URL object from a URL string, and then creating a URLSessionDataTask object to perform the GET request. The URLSessionDataTask completion closure returns three parameters - data, response, and error. We’re checking for the presence of data and then parsing the JSON data using JSONSerialization.

This is just a basic example and there is a lot more that URLSession can do. For example, you can use different HTTP methods (e.g. POST, PUT, DELETE), set headers, handle cookies, and more.

gistlibby LogSnag