Logo for tanaschita.com

How to use async/await in SwiftUI

Learn how 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
  • the user taps a button
  • the user pulls 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 static async function.

Button("refresh status") {
async {
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.

Related tags

Written by

Articles with related topics

Latest articles and tips