Skip to Content
Course content

84: async/await with URLSession

Click on the "Edit" button in the top corner of the screen to edit your slide content.

For a long time, the standard way to grab data from the web in Swift was using dataTask(with:completionHandler:). If you've spent any time in older codebases, you've seen it everywhere. It works, but it forces you into a mental model of "I'll tell you when I'm done" rather than "give me the result." When you start chaining multiple network requests—say, fetching a user's profile and then using that profile ID to fetch their recent posts—you end up in what we call "callback hell," where your code drifts further and further to the right of the screen.

The Callback Labyrinth

Let's look at a naive implementation of a user profile fetcher. Imagine we're hitting an API to get a User object. In the old way, the logic is fragmented. You have to handle the error, the response, and the data as three separate optional values, which is honestly a bit of a design mess.

func fetchUser(id: Int, completion: @escaping (Result<User, Error>) -> Void) {
    let url = URL(string: "https://api.example.com/users/\(id)")!
    
    URLSession.shared.dataTask(with: url) { data, response, error in
        if let error = error {
            completion(.failure(error))
            return
        }
        
        guard let data = data else {
            completion(.failure(URLError(.badServerResponse)))
            return
        }
        
        do {
            let user = try JSONDecoder().decode(User.self, from: data)
            completion(.success(user))
        } catch {
            completion(.failure(error))
        }
    }.resume()
}

I've written this pattern a thousand times, and the biggest risk isn't the complexity—it's the human error. It is incredibly easy to forget to call completion() in one of those guard blocks. If you do that, the calling code just hangs forever, waiting for a response that will never come. There's no compiler warning for this; your app just stops reacting, and you're left staring at a loading spinner until you find the missing line of code.

Flattening the Logic with async/await

With async/await, we stop treating the network request as a "task to be started" and start treating it as a "value to be awaited." URLSession now provides a much cleaner method: data(from:delegate:). This doesn't take a completion handler; it simply returns a tuple containing the data and the response, or it throws an error.

func fetchUser(id: Int) async throws -> User {
    let url = URL(string: "https://api.example.com/users/\(id)")!
    
    // The execution pauses here until the request finishes
    let (data, _) = try await URLSession.shared.data(from: url)
    
    return try JSONDecoder().decode(User.self, from: data)
}

Notice how the "pyramid of doom" has completely vanished. The code reads top-to-bottom, exactly how it executes. I love this because the error handling is now centralized. If the network fails, URLSession throws. If the JSON is malformed, JSONDecoder throws. Instead of five different if let or guard statements, you just wrap the call to fetchUser in a single do-catch block at the call site.

The Cost of the Switch

Now, you might wonder if this is just syntactic sugar. It's more than that. The old dataTask approach relies on closures that capture self, which often leads to memory leaks (strong reference cycles) if you aren't careful with [weak self]. With async/await, the Swift runtime manages the suspension point. The function "pauses," frees up the thread for other work, and resumes when the data arrives.

The only real "cost" is that you have to be mindful of the context. You can't call an async function from a synchronous one without creating a Task. But in a modern SwiftUI or UIKit app, this is almost always the trade-off you want. You're trading a tiny bit of setup overhead for a massive gain in maintainability and a total elimination of the "forgotten completion handler" bug.




📋 Practical Task

Exercise: Build an Async GitHub User Lookup

Your goal is to create a service that fetches a user's public profile from the GitHub API. You will move away from completion handlers and implement a fully asynchronous flow.

Requirements:

  • Define a GitHubUser struct that conforms to Codable, containing at least the login (username) and public_repos (number of repositories) fields.
  • Write an async function called fetchGitHubProfile(for username: String) that:
    • Constructs a URL using "https://api.github.com/users/\(username)".
    • Uses URLSession.shared.data(from:) to fetch the data.
    • Decodes the resulting data into a GitHubUser object.
    • Throws an error if the network request fails or the decoding fails.
  • Create a Task block to call this function for a real GitHub username (e.g., "apple") and print the number of public repositories to the console. Wrap this call in a do-catch block to handle potential errors gracefully.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.