create http get request in swift

To create an HTTP GET request in Swift, we need to use the URLRequest and URLSession classes.

main.swift
// create url endpoint
let urlString = "https://jsonplaceholder.typicode.com/posts"
guard let url = URL(string: urlString) else { return }

// create url request with HTTP method as GET
var request = URLRequest(url: url)
request.httpMethod = "GET"

// create URL session with shared session
let session = URLSession.shared

// create data task for GET request
let task = session.dataTask(with: request) { (data, response, error) in
    // handle response
}

// start task
task.resume()
486 chars
19 lines

In this example, we first create a URL endpoint as a String and convert it to a URL object. We then create a URLRequest object and set its HTTP method to GET.

Next, we create a URLSession object using the shared session. Finally, we create a URLSessionDataTask object with the dataTask(with:completionHandler:) method and pass in our URLRequest object.

Inside the completionHandler, we can handle the response data, response metadata, and any errors that may occur during the request. To handle errors gracefully, we can use Swift's do-catch statement or an optional binding to safely unwrap any optional values.

gistlibby LogSnag