import SwiftUI
struct AsyncGreetingView: View {
@State private var greeting: String = ""
@State private var isLoading: Bool = false
var body: some View {
VStack(spacing: 20) {
Text("Async Greeting Screen")
.font(.title)
Button("Fetch Greeting") {
Task {
isLoading = true
greeting = await fetchGreeting()
isLoading = false
}
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
if isLoading {
ProgressView()
}
Text("Greeting: \(greeting)")
.font(.headline)
Spacer()
}
.padding()
}
func fetchGreeting() async -> String {
try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
return "Hello from async!"
}
}
struct AsyncGreetingView_Previews: PreviewProvider {
static var previews: some View {
AsyncGreetingView()
}
}We created an async function fetchGreeting() that waits 2 seconds using Task.sleep and then returns a greeting string.
The button action uses Task to run async code. Inside, it sets isLoading to true, then calls await fetchGreeting() to wait for the greeting, updates the greeting state, and finally sets isLoading to false.
This shows a loading spinner while waiting and updates the UI with the greeting once ready.