How do I call async APIs from SwiftUI lifecycle methods?

In SwiftUI, you can call asynchronous APIs within the lifecycle methods such as `onAppear`. This is useful for fetching data when a view appears on the screen. Below is an example of how you can do this using Swift's `async`/`await` features.

When using asynchronous code, make sure to handle any possible errors gracefully and update your UI accordingly.

<?php import SwiftUI struct ContentView: View { @State private var data: String = "" @State private var isLoading: Bool = false var body: some View { VStack { if isLoading { ProgressView() } else { Text(data) } } .onAppear { Task { await fetchData() } } } func fetchData() async { isLoading = true do { let url = URL(string: "https://api.example.com/data")! let (data, _) = try await URLSession.shared.data(from: url) self.data = String(data: data, encoding: .utf8) ?? "No data" } catch { print("Error fetching data: \(error)") } isLoading = false } } ?>

SwiftUI async APIs lifecycle methods onAppear async/await URLSession fetching data