In this demo, you’ll update some SwiftUI code to make use of Asynchronous methods.
Open TheMet app in the Starter folder.
You’ll immediately notice that something’s wrong with the app when running. The spinner in the middle of the screen doesn’t stop spinning. You need to fix that.
Can you tell what the issue is? That’s right, the ContentView isn’t receiving any data from the network. To do that, you need to use a task() modifier.
First, open ContentView and add the task() modifier with an empty closure at the end of the NavigationStack. Inside the closure is where your asynchronous code will go.
.task {
}
Now add the call to store.fetchObjects() inside the task modifier, passing in the query the screen receives to search the Met API.
.task {
do {
try await store.fetchObjects(for: query)
} catch {}
}
Run the app again. Hey, that looks a lot better!
Next, let’s double check the app is using tasks and fetching data asynchronuously as expected.
Select Xcode from the menu bar, then open Developer Tool, and click on Instruments.
When instruments opens, select the Swift Concurrency option and click Choose.
Next, make sure instruments is analyzing the app by attaching it to the app process running in the simulator.
Next, run the app for a few moments and make a new query for items in the app. Meanwhile, keep an eye on that instruments window.
Instruments picked up some tasks!
Using the summary, you can drill down and see where the tasks are running and what state they’re in.
This is useful to see what your app is doing at particular moments in time. For this example, we can see TheMetStore.fetchObjects is being called, which is what we expect since we just added the call to a task.
With that, you’ve fixed the app by making an asynchronous data call, and learnt how to use Instruments to check the app is using tasks as expected.