Skip to content

Lesson 7 of 9 · 28m

URLSession Networking That Respects Reality

Build a small networking layer with explicit requests, decoding boundaries, retries, cancellation, authentication, and offline-aware behavior.

Mobile networking is not server networking with smaller endpoints. Radios sleep, captive portals intercept traffic, users switch networks mid-request, and a response can arrive after the user leaves the screen. A professional networking layer accepts those conditions instead of pretending JSON decoding is the whole job.

Start with an explicit request boundary

Do not scatter URL(string:) and ad hoc headers through view models. Put authentication, validation, decoding, logging, and retry policy in known places:

struct APIClient: Sendable {
    let session: URLSession
    let baseURL: URL
    let decoder: JSONDecoder
    func send<Response: Decodable>(_ request: APIRequest<Response>) async throws -> Response {
        var urlRequest = URLRequest(url: baseURL.appending(path: request.path))
        urlRequest.httpMethod = request.method
        urlRequest.httpBody = request.body
        urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
        let (data, response) = try await session.data(for: urlRequest)
        try validate(response: response, data: data)
        return try decoder.decode(Response.self, from: data)
    }
}

The exact abstraction matters less than having one boundary instead of twelve feature-specific interpretations.

Validate transport before decoding

HTTP errors are not decoding errors:

enum APIError: Error {
    case unacceptableStatus(Int, Data)
    case invalidResponse
    case decodingFailed(Error)
}

Capture status code, response excerpt, request ID, and endpoint in logs. Do not log bearer tokens, refresh tokens, authorization headers, or sensitive payloads.

Retry is a policy, not a loop

Retries make sense for idempotent reads and mutations protected by idempotency keys. They are dangerous for purchases, posts, and operations whose server-side effect is unknown after timeout:

for attempt in 0..<3 {
    do { return try await operation() }
    catch where attempt < 2 {
        try await Task.sleep(for: .milliseconds(300 * (attempt + 1)))
    }
}

Production policy also needs jitter, cancellation checks, and error classification. Do not retry validation failures as if the server will change its mind out of pity.

Offline is behavior, not an error code

NSURLErrorNotConnectedToInternet is only one symptom. Decide what can be read from cache, what can be queued, what must fail, and what needs conflict handling later. Save form drafts locally. Return fresh data and stale fallback explicitly instead of silently presenting old data as current.

Authentication needs lifecycle awareness

Attach tokens in one place, refresh them in one serialized path, and never leak them into analytics or crash breadcrumbs. Handle 401 as an authentication signal, not a universal retry instruction; a revoked token can fail forever while your client burns battery in a loop.

Field notes

  • Know whether URLSession work is view-owned, app-owned, or background-capable before choosing the API shape.
  • TLS pinning is rarely the first control a normal app needs and can become an outage when certificates rotate badly.
  • Measure on cellular networks. Office Wi-Fi hides timeouts users see daily.
  • Never mutate shared caches without actor isolation or another synchronization strategy.

Was this lesson helpful?

Sign in to rate