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()
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?