get request in swift in swift

Here's an example of making a GET request in Swift:

main.swift
// Create a URL object from the string
guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1") else {
    print("Error: URL is invalid")
    return
}

// Create a URLRequest object with the URL
let request = URLRequest(url: url)

// Create a URLSession data task with the request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    // Handle response
    if let error = error {
        print("Error: \(error)")
    } else if let data = data {
        // Convert response data to string
        let responseString = String(data: data, encoding: .utf8)
        print("Response: \(responseString ?? "")")
    }
}

// Start the data task
task.resume()
702 chars
24 lines

In the above example, we first create a URL object from a string representing the endpoint of the API we want to retrieve data from. We then create a URLRequest object with the URL, which we pass to a URLSession data task to handle the network request. The dataTask method takes a closure that will be called when the task has completed, with the response data, response metadata, and any error that occurred during the request.

In the closure, we first check for any errors that occurred during the request. If there were no errors, we check if we have any data in the response, and if so, we convert that data to a string, which we can then print out or use for further processing. Finally, we call the resume method of the data task to start the network request.

gistlibby LogSnag