URLSession
is a class that manages tasks related to network data transfers. You use URLSession
when you want to download or upload data to an HTTP server.
Combined with Codable
types, URLSession
provides a very convenient abstraction over your network requests, if you're using a JSON-based API, for example. In this section, we'll look at how we can use Encodable
and Decodable
to represent request and responses bodies in a generic and compile time-safe manner.
Let's take a look at the anatomy of a simple URL task:
let url = URL(string: "https://api.website.com/")! let task = URLSession.shared.dataTask(url: url) { data, response, error in if let error = error { return } // handle the error somehow guard let response = response as HTTPURLResponse, let data = data else { return } // data: Data is set, and all good } task.resume()
If the call has succeeded, the data variable will be set and will contain the data downloaded...