With URLSession's async data(for:) on iOS, how do you fetch and decode a JSON list, and why must you check the HTTP status code yourself?
answer
- transport failure versus server answer
- the tuple a single await returns
- cast URLResponse to its HTTP subclass
- statusCode range before decoding
basics
~10 sAwait URLSession.shared.data(for: request), cast the returned URLResponse to HTTPURLResponse, require a 200-299 statusCode, then decode the Data. data(for:) throws when the transfer fails, not because the server answered 404 or 500.
solid answer
~40 sI build a `URLRequest`, call `try await URLSession.shared.data(for: request)` and get back a `(Data, URLResponse)` tuple once the whole body has arrived. The call throws, usually a `URLError`, when the transfer itself fails: no connection, a timeout, a cancelled task. A 404 or a 503 is not a transfer failure, so it comes back as an ordinary response with an error body. That is why I cast the response with `as? HTTPURLResponse`, check that `statusCode` is in `200...299`, and only then hand the `Data` to `JSONDecoder`. `data(for:delegate:)` is iOS 15; the overload without a delegate is marked available from iOS 13, so an iOS 17 app can use either.
code
swift · 29 linesimport Foundation
struct Departure: Decodable, Sendable {
let line: String
let minutes: Int
}
enum DeparturesError: Error {
case notHTTP
case badStatus(Int)
}
func fetchDepartures(stopID: String) async throws -> [Departure] {
var components = URLComponents(string: "https://api.example.com/departures")!
components.queryItems = [URLQueryItem(name: "stop", value: stopID)]
let request = URLRequest(url: components.url!)
// Throws only for transport failures: no network, timeout, cancellation.
let (data, response) = try await URLSession.shared.data(for: request)
// A 404 or 503 arrives here as a normal response.
guard let http = response as? HTTPURLResponse else {
throw DeparturesError.notHTTP
}
guard (200...299).contains(http.statusCode) else {
throw DeparturesError.badStatus(http.statusCode)
}
return try JSONDecoder().decode([Departure].self, from: data)
}go deeper
Recall the shape: build a URLRequest, await data(for:), cast to HTTPURLResponse, check 200-299, decode. Say out loud that a 404 does not throw.
Explain which failures surface as thrown URLError codes and which arrive as normal responses, and why the async call needs no resume() while dataTask(with:) does.
Show the error mapping you would ship: transport codes to offline or retry states, server statuses to domain errors, and decoding failures logged with the status and URL.
Discuss where status validation lives so every feature gets it once, and when the shared session stops being enough because a feature needs its own timeouts or caching rules.
## What `data(for:)` gives you `URLSession` is Foundation's HTTP client, and `data(for:)` is the shortest way to use it from Swift concurrency. You pass a **`URLRequest`** (URL, method, headers, body, cache policy, timeout) and suspend until the session has received the whole response body. The call then returns a tuple: - **`Data`**: the response body, whatever the server sent, including an error page. - **`URLResponse`**: the response metadata. For `http` and `https` requests it is an **`HTTPURLResponse`**, the subclass that adds `statusCode` and `allHeaderFields`, which is why code casts it with `as?` rather than force-casting. Two declarations matter for availability. `data(for:delegate:)`, which takes an optional per-task delegate, is declared for **iOS 15**. The Swift overlay also declares `data(for:)` without the delegate parameter as available from **iOS 13**: on iOS 15 and later it forwards to the delegate version, and on iOS 13 and 14 it wraps a classic data task. An app with an iOS 17 deployment target can call either. `URLSession.shared` is the singleton session. It has no configuration you can change and no session delegate, which is fine for a simple GET. Anything that needs custom timeouts, caching rules or delegate callbacks needs a session you create yourself. ## Transport errors versus server errors The key idea is that **an HTTP error status is a successful transfer**. The client sent a request and the server answered it; the answer happens to say "not found". | Situation | What `data(for:)` does | How you detect it | |---|---|---| | No network | throws `URLError` (`.notConnectedToInternet`) | `catch` | | No data within the request timeout | throws `URLError` (`.timedOut`) | `catch` | | The surrounding task is cancelled | throws | `catch` | | Server answers 404 or 503 | returns `(Data, URLResponse)` | check `statusCode` | | Server answers 200 | returns `(Data, URLResponse)` | decode | Apple's article on fetching website data into memory describes the same two checks for the completion-handler API: first see whether the `error` parameter is set (a transport error), then verify that the response's status code indicates success and that its MIME type is the one you expect (a server error). The async API folds the first check into `throws`, but the second one is still your job. ## A complete fetch, step by step 1. Build the URL with `URLComponents` so query values are escaped for you. 2. Wrap it in a `URLRequest`; set the method or headers here if needed. 3. `try await` the session's `data(for:)`. 4. Cast to `HTTPURLResponse` and reject any status outside `200...299` with your own error. 5. Decode the `Data` with `JSONDecoder` into a `Decodable` type. ```swift struct Departure: Decodable, Sendable { let line: String let minutes: Int } enum DeparturesError: Error { case notHTTP case badStatus(Int) } func fetchDepartures(stopID: String) async throws -> [Departure] { var components = URLComponents(string: "https://api.example.com/departures")! components.queryItems = [URLQueryItem(name: "stop", value: stopID)] let request = URLRequest(url: components.url!) let (data, response) = try await URLSession.shared.data(for: request) guard let http = response as? HTTPURLResponse else { throw DeparturesError.notHTTP } guard (200...299).contains(http.statusCode) else { throw DeparturesError.badStatus(http.statusCode) } return try JSONDecoder().decode([Departure].self, from: data) } ``` Key strategies, date strategies and tolerant decoding are Codable topics, covered in the lesson on Codable and serialization; the networking half ends once you have verified `Data` in hand. ## Where the code runs - An `async` function resumes on its own isolation after the `await`. Called from a `@MainActor` view model, the code after `data(for:)` runs on the main actor, so assigning the decoded list to a published property is safe there. - The older `dataTask(with:completionHandler:)` behaves differently: Apple's documentation warns that its completion handler runs on a different dispatch queue from the one that created the task, so UI updates must hop to the main queue explicitly. - A task created with `dataTask(with:)` starts suspended and does nothing until you call `resume()`. The async methods create and start the task for you. ## Mistakes a reviewer catches - Decoding before checking the status, so a JSON error body turns into a confusing `DecodingError`. - Treating non-empty `Data` as success; error pages have bodies too. - Force-casting the response with `as!`, which crashes for a non-HTTP URL. - Showing a "network error" alert for a 401, when the server answered and the app should react to that status. - Creating a new `URLSession` for every call instead of reusing `shared` or one long-lived session. - Skipping the MIME type check that Apple's own sample performs, so an HTML captive-portal page reaches the JSON decoder. - Logging the whole body of a failed response, which may hold personal data; the status code and URL are usually enough.
- How would the same fetch look with dataTask(with:completionHandler:), and what changes?The handler receives optional `data`, `response` and `error`. You check `error` first, then the `HTTPURLResponse` status, exactly as with the async call, but you must call `resume()` on the returned task or nothing happens, and the handler runs on a background dispatch queue, so any UI update needs `DispatchQueue.main.async` or a hop to the main actor.
- How do you tell 'no connection' from 'the server is slow' when data(for:) throws?Catch `URLError` and read its `code`. `.notConnectedToInternet` means the device had no usable route when the connection was set up; `.timedOut` means the request timer expired without new data; `.networkConnectionLost` means an established connection dropped. Each deserves different copy: offline state, a retry prompt, or a silent retry.
- data(for:) throws an error when the server answers 404
- Non-empty Data from data(for:) proves the request succeeded
- You must call resume() after awaiting data(for:)
- The completion handler of dataTask(with:completionHandler:) runs on the main queue
- Force-casting the URLResponse to HTTPURLResponse is always safe