How to use async/await in SwiftUI
Learn to use view modifiers to call async/await methods in SwiftUI.
12 Sep 2021 · 2 min read
Depending on the scenario, there are different ways to use Swift's async/await syntax in SwiftUI. We might want to call an asynchronious function for example when:
- a SwiftUI view appears
- as a response to a user action like a button tap or a pull to refresh
Using the task view modifier
In the scenario where we want to do some asynchronious work when a view appears, SwiftUI provides the task modifier.
var body: some View {Text(viewModel.status).task {await viewModel.refreshStatus()}}
In the example above, as soon as the Text view appears, SwiftUI will create a task and will also cancel it when the view disappears.
Calling the async static function
In the scenario where we want to do some asynchronious work when the user taps a button, we can use the Task type.
Button("refresh status") {Task {await viewModel.refreshStatus()}}
Using the refreshable view modifier
In the scenario where we want to refresh some data on a pull to refresh, we can use the refreshable modifier.
List {...}.refreshable {await viewModel.refreshMessages()}
The modifier takes an async action that SwiftUI will execure as soon as the user performs the refresh gesture.

Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips