How do I use URLSession for HTTP requests in Swift?

Using URLSession for HTTP requests in Swift is straightforward and efficient. This framework provides an API for downloading data from and uploading data to endpoints using URL requests. Below is a simple example demonstrating how to perform a GET request to fetch JSON data from a web API.

import Foundation // Create a URL object guard let url = URL(string: "https://api.example.com/data") else { return } // Create a URLSession data task let task = URLSession.shared.dataTask(with: url) { (data, response, error) in // Check for errors if let error = error { print("Error: \(error.localizedDescription)") return } // Check for valid response and data guard let data = data, let response = response as? HTTPURLResponse, response.statusCode == 200 else { print("Invalid response or data.") return } // Process the data (for example, decode it into a model) do { let json = try JSONSerialization.jsonObject(with: data, options: []) print("Response JSON: \(json)") } catch { print("Failed to decode JSON: \(error.localizedDescription)") } } // Start the task task.resume()

Swift URLSession HTTP requests GET request API JSON data parsing