Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 46 ยท Data, Networking and Persistence

Networking with URLSession and async/await

Fetch data in a SwiftUI app with URLSession and async/await: status codes, typed errors, an idle/loading/loaded/failed state enum, cancellation and App Transport Security.

Networking is where an app meets the unpredictable: slow connections, servers that return errors, users who leave the screen before the answer arrives. Swift's async/await makes the code read top to bottom, but good networking still needs decisions about errors, loading states and cancellation.

This lesson uses URLSession to fetch and decode data, and builds the pattern you will reuse in every app: a small state enum that a SwiftUI view renders. The real network code is read-only because the site's runner has no network. The TryIts replace the network with a fake transport, so every state and error path runs here and now.

A request has a life

Idle Nothing requested yet.
Loading Waiting for the server.
Loaded Decoded data is ready.
Failed Show a message and a retry.

Model these four states explicitly. The view then just switches on them.

1 / 2

The basic call

URLSession has async methods that return the body and the response together. Here is the whole flow in a function:

Swift
import Foundation

struct Post: Decodable, Identifiable {
    let id: Int
    let title: String
}

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

    guard let http = response as? HTTPURLResponse else {
        throw URLError(.badServerResponse)
    }
    guard (200..<300).contains(http.statusCode) else {
        throw URLError(.badServerResponse)
    }
    return try JSONDecoder().decode([Post].self, from: data)
}

Four steps happen in order, and each can throw:

  1. Send with try await. The function suspends while the request is in flight, and the thread is free to do other work. If the device is offline you get a URLError.
  2. Check the response type. For HTTP it is an HTTPURLResponse.
  3. Check the status code. This is the step beginners forget. URLSession does not throw for a 404 or a 500. From its point of view the server answered correctly. You must inspect the status yourself.
  4. Decode the body, as in the Codable lesson.

For more control, build a URLRequest (method, headers, body, timeout) and call data(for:). For a POST you set httpMethod = "POST", add a Content-Type: application/json header and set httpBody to encoded data.

Never force-unwrap URLs built from user input: URL(string:) returns nil for invalid text. A hard-coded constant URL is the one place where ! is acceptable, and URLComponents is safer when you add query items.

Typed errors

Throwing a bare URLError for everything hides useful detail. Define your own error type with the cases your UI cares about:

Swift
enum APIError: Error {
    case offline
    case server(statusCode: Int)
    case invalidData
    case cancelled
}

Then translate low-level errors in one place, so the rest of the app only sees APIError:

Swift
func mapError(_ error: Error) -> APIError {
    if let api = error as? APIError { return api }
    if error is DecodingError { return .invalidData }
    if let urlError = error as? URLError {
        switch urlError.code {
        case .notConnectedToInternet, .networkConnectionLost, .timedOut:
            return .offline
        case .cancelled:
            return .cancelled
        default:
            return .offline
        }
    }
    if error is CancellationError { return .cancelled }
    return .invalidData
}

A loading state enum

A view needs to answer one question: what do I draw right now? Avoid several loose booleans (isLoading, hasError, items) that can contradict each other, such as loading and failed at once. Use one enum:

Swift
enum LoadState<Value> {
    case idle
    case loading
    case loaded(Value)
    case failed(String)
}

Now the SwiftUI view is a plain switch:

Swift
struct PostsView: View {
    @State private var state: LoadState<[Post]> = .idle

    var body: some View {
        Group {
            switch state {
            case .idle:
                Color.clear
            case .loading:
                ProgressView("Loading...")
            case .loaded(let posts):
                List(posts) { post in
                    Text(post.title)
                }
            case .failed(let message):
                ContentUnavailableView {
                    Label("Couldn't load posts", systemImage: "wifi.slash")
                } description: {
                    Text(message)
                } actions: {
                    Button("Try again") { Task { await load() } }
                }
            }
        }
        .task { await load() }
    }

    private func load() async {
        state = .loading
        do {
            state = .loaded(try await loadPosts())
        } catch {
            state = .failed("Check your connection and try again.")
        }
    }
}

The .task modifier starts the work when the view appears and cancels it automatically when the view disappears, which brings us to cancellation. The lifecycle details are in View Identity and Lifecycle.

Running the whole thing without a network

To test code that talks to a server, hide the network behind a protocol. The real implementation wraps URLSession. A fake one returns canned data, so you can exercise every branch, including the failures that are hard to trigger on demand. This is the idea from The Environment and Dependency Injection applied to networking.

Swift A fake transport and every outcome

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

All five outcomes ran in milliseconds, without a server. In an app, the real transport would call URLSession, and the same APIClient would drive your view model.

The state enum in motion

Swift idle, loading, loaded, failed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each assignment to state is a moment where SwiftUI would re-render. Because the enum holds exactly one case at a time, the screen can never show a spinner and an error together.

Cancellation

Users scroll away, switch tabs, or type a new search term while the old request is still running. Work that no longer matters should stop. Structured concurrency handles this through cooperative cancellation:

  • A Task can be cancelled. The .task modifier cancels its task when the view disappears.
  • URLSession's async methods notice cancellation and throw URLError(.cancelled) (the error may also surface as CancellationError in other async code).
  • Your own long loops should call try Task.checkCancellation() so they stop promptly.

Cancellation is not a failure to show the user. Treat it as "nothing to do": do not replace the screen with an error message when the task was cancelled. That is why mapError above has a .cancelled case you can ignore in the view model.

For search-as-you-type, the classic bug is a stale response: the request for "ca" finishes after the request for "cat" and overwrites the newer results. Keep the current search task in a property, cancel it when the text changes, and start a new one.

Swift Cancelling an outdated request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first search is cancelled while it sleeps, so only the newest results ever reach the screen. In a real app the box would be a @MainActor view model. The threading rules are covered in Concurrency in iOS: MainActor, Tasks and Async Work.

App Transport Security

Apple expects network traffic to use HTTPS. App Transport Security (ATS) enforces this: by default, a plain http:// request is blocked and fails with an error. It also requires modern TLS settings.

  • Use HTTPS endpoints. For development servers you can add narrow, per-domain exceptions in Info.plist.
  • Avoid the blanket "allow arbitrary loads" switch. App Review may ask you to justify it, and it weakens security for every request.
  • Local network servers and special cases have their own, specific exceptions. Add only what you need.

Other practical details: set a reasonable timeoutInterval on requests, mark API calls that can be retried safely (GET) separately from ones that cannot (POST that creates something), and never log tokens. Secrets such as API tokens belong in the Keychain, as covered in Keychain, Biometrics and App Security.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A server answers 404 Not Found. What does try await URLSession.shared.data(from:) do?

    URLSession reports transport errors, not HTTP errors. A 404 is a valid response, so you check statusCode yourself.
  2. 2. Why use an enum like LoadState instead of separate isLoading and error booleans?

    With separate flags you can end up loading and failed at once. One enum makes the view a simple switch and removes impossible states.
  3. 3. What is the main benefit of hiding URLSession behind a protocol?

    A protocol lets tests and previews inject canned responses, including offline and server errors that are hard to trigger for real.
  4. 4. The .task modifier is attached to a view. What happens to its work when the view disappears?

    task(_:) ties the work to the view's lifetime and cancels it on disappearance, which avoids wasted requests.
  5. 5. A user types 'ca' then 'cat' quickly. Which approach avoids showing results for 'ca' after those for 'cat'?

    Cancel the outdated task so its late response cannot overwrite newer results.

Summary

  • try await URLSession.shared.data(from:) returns data and a response; check the status code yourself, because HTTP errors do not throw.
  • Convert low-level errors into your own APIError type in one place.
  • Model the screen with an idle/loading/loaded/failed enum and render it with a switch.
  • Hide the network behind a protocol so a fake transport can drive tests and previews.
  • Cancellation is cooperative; .task cancels on disappearance, and cancelled work is not an error to display.
  • ATS requires HTTPS by default; keep exceptions narrow.

Next: MVVM and App Architecture in SwiftUI