SwiftUI async/await: load data with .task and URLSession
SwiftUI async/await explained: fetch JSON with URLSession, start the request with the .task modifier and show loading and error states properly.
You load data from the network in SwiftUI with two building blocks: an async function that fetches with URLSession and decodes with JSONDecoder, and the .task modifier, which starts that function as soon as the view appears. When the view goes away, SwiftUI cancels the request automatically.
That means no completion handlers and no cleanup of your own. This post goes from the first request to proper loading and error states.
Fetching JSON with async/await
Start with the model: a struct that is Decodable and whose properties are named like the fields in the JSON. The loading function is marked async and throws, because it has to wait and can fail.
struct Post: Decodable, Identifiable {
let id: Int
let title: String
}
func loadPosts() async throws -> [Post] {
let url = URL(string: "https://example.com/api/posts")!
let (data, response) = try await URLSession.shared.data(from: url)
guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
throw URLError(.badServerResponse)
}
return try JSONDecoder().decode([Post].self, from: data)
}The await keyword marks the point where the code waits. The interface stays responsive meanwhile. Always check the status code: a server error page returns data too, just not the data you expect.
The .task modifier: load when the view appears
.task is the asynchronous counterpart to onAppear. You can use await directly inside it.
struct PostsView: View {
@State private var posts: [Post] = []
var body: some View {
List(posts) { post in
Text(post.title)
}
.task {
do {
posts = try await loadPosts()
} catch {
print("Loading failed: \(error)")
}
}
}
}- The task starts when the view appears.
- It is cancelled when the view disappears, for example when going back in a NavigationStack.
- Changes to @State trigger a redraw as usual.
Showing loading and error states
An empty list says nothing about whether data is still loading or something went wrong. A state with three cases that the view renders with a switch is better.
enum LoadState {
case loading
case loaded([Post])
case failed(String)
}
struct PostsView: View {
@State private var state: LoadState = .loading
var body: some View {
Group {
switch state {
case .loading:
ProgressView("Loading …")
case .loaded(let posts):
List(posts) { Text($0.title) }
case .failed(let message):
ContentUnavailableView("No connection",
systemImage: "wifi.slash",
description: Text(message))
}
}
.task { await load() }
}
func load() async {
do {
state = .loaded(try await loadPosts())
} catch {
state = .failed(error.localizedDescription)
}
}
}This rules out impossible in-between states such as loading and failed at the same time. How to make the loaded items searchable and add pull to refresh is covered in SwiftUI List.
Reloading with .task(id:)
If you pass .task a value as its id, the task restarts whenever that value changes, and the previous one is cancelled. That is ideal for a search that reloads on every keystroke.
.task(id: query) {
try? await Task.sleep(for: .milliseconds(300))
guard !Task.isCancelled else { return }
await search(for: query)
}The short pause keeps every single letter from firing a request. If the person keeps typing, the waiting task is cancelled and never sent.
Common mistakes
- A Task inside onAppear: If you start a Task there yourself, you also have to cancel it yourself. .task does that for you.
- Showing cancellation as an error: When the task is cancelled, URLSession throws. Don't show an error message for that.
- Piling logic into the view: Once there is more than one request, loading belongs in its own class. The post on @Observable shows how.
- Reloading every time: .task runs on every appearance. Check whether the data is already there, or store it locally, for example with SwiftData.