Networking

5 concepts · 10 practice questions

URLSession and background transfers

URLSession's async data(for:) returns the body and the response, and it throws only for transport failures, such as no connection or a timeout. A 404 or a 500 is a completed round trip, so check the HTTP status code yourself. Reuse one session so connections are pooled. For large uploads and downloads that must continue after the user leaves the app, use a background session configuration: the system performs the transfer and wakes or relaunches the app to deliver the result.

func fetchUser(id: String) async throws -> User {
    var request = URLRequest(url: baseURL.appending(path: "users/\(id)"))
    request.setValue("application/json", forHTTPHeaderField: "Accept")

    let (data, response) = try await session.data(for: request)
    guard let http = response as? HTTPURLResponse else { throw APIError.invalidResponse }
    guard (200..<300).contains(http.statusCode) else { throw APIError.status(http.statusCode) }
    return try decoder.decode(User.self, from: data)
}

let background = URLSessionConfiguration.background(withIdentifier: "com.example.uploads")

Also covered

Codable and JSON
Errors and retries
Caching responses and images
Auth tokens and refresh

Sign in to read the rest and take the 10-question test.

Sign in to continue