Logo for tanaschita.com

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.

Sponsorship logo
Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

async/await

concurrency

swift

How to bridge completions handlers to Swift's async/await

Understand Swift continuations to create your own async/await functions.

05 Dec 2022 · 3 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum