Networking introduces transport failure, decoding failure, cancellation and stale results. A successful response path alone cannot explain what the screen does after a request is replaced or cancelled.

Request → Validate response → Decode model → Publish current result
  1. 1Request
  2. 2Validate response
  3. 3Decode model
  4. 4Publish current result

Work through the example

Inject a network service and exercise a delayed response, malformed payload and cancellation. Keep UI mutations on the intended actor.

Start with a disposable branch and synthetic data. Write the expected outcome before changing the implementation, then keep the first failing result. This prevents a later repair from quietly redefining the task. The procedure below is grounded in the repository reference; its examples must still be checked against your project and installed toolchain.

Implementation reference

The following focused section is adapted from the maintained project guide. It preserves the source’s examples and limitations.

URLSession Async/Await Patterns

// GET request
func fetchUsers() async throws -> [User] {
    let url = URL(string: "https://api.example.com/users")!
    let (data, response) = try await URLSession.shared.data(from: url)

    guard let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode) else {
        throw APIError.badResponse
    }
    return try JSONDecoder().decode([User].self, from: data)
}

// POST request
func createUser(_ user: CreateUserRequest) async throws -> User {
    var request = URLRequest(url: URL(string: "https://api.example.com/users")!)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try JSONEncoder().encode(user)

    let (data, response) = try await URLSession.shared.data(for: request)

    guard let http = response as? HTTPURLResponse, http.statusCode == 201 else {
        throw APIError.badResponse
    }
    return try JSONDecoder().decode(User.self, from: data)
}

// Download with progress using AsyncBytes
func downloadWithProgress(from url: URL) async throws -> Data {
    let (bytes, response) = try await URLSession.shared.bytes(from: url)

    guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
        throw APIError.badResponse
    }

    let totalBytes = Int(http.expectedContentLength)
    var data = Data(capacity: totalBytes)

    for try await byte in bytes {
        data.append(byte)
        let progress = Double(data.count) / Double(totalBytes)
        await MainActor.run { self.downloadProgress = progress }
    }
    return data
}

Acceptance and failure review

Checkpoint What to inspect If it does not match
Request Confirm the input and environment Preserve the failure and return to this step
Validate response Inspect the intermediate artifact Preserve the failure and return to this step
Decode model Run the focused check Preserve the failure and return to this step
Publish current result Record the observed result Preserve the failure and return to this step

Ask the agent to explain the smallest change that resolves the observed mismatch. Keep unrelated refactors out of the repair. A change that makes a warning disappear is not enough if the behavior or ownership contract has changed. Re-run the same acceptance check so the before and after results are comparable.

Evidence and limits

This chapter's networking exercise is not a new recorded network integration test.

This is an educational guide. Its presence in the series does not certify a completed client-specific lab. The series evidence record separates executed checks from exercises and blocked environments.

Inspect the source used in this lesson.

What to do next

Next: Navigation in SwiftUI: what agents get wrong with NavigationStack