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
}
}
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?