Integrating SwiftUI and an async function
As mentioned in the introduction of this chapter, the async
await
model fits well in the SwiftUI model.
SwiftUI views offer support for calling asynchronous functions. Also, while a function is concurrently executing, we can change the view without having it blocked.
In this short recipe, we'll integrate an async
function that suspends its execution for a few seconds, and at the same time, we can use a button to increase a counter shown in the view.
Getting ready
Create an iOS 15 SwiftUI app called AsyncAwaitSwiftUI
.
How to do it…
We will create a simple app with a button that increases a counter and an asynchronous function that blocks for 5 seconds before returning a value to be presented in the view.
The steps are as follows:
- Create a
Service
class with the following two functions:class Service { func fetchResult() async -> String { ...