Skip to content

Instantly share code, notes, and snippets.

@geraldWilliam
Last active April 26, 2024 19:23
Show Gist options
  • Save geraldWilliam/8f9ef479865ae4eff556eb3ba64e8ef8 to your computer and use it in GitHub Desktop.
Save geraldWilliam/8f9ef479865ae4eff556eb3ba64e8ef8 to your computer and use it in GitHub Desktop.
Await User Interaction
//
// ContentView.swift
// Confirmator
//
// Created by Gerald Burke on 4/26/24.
//
import SwiftUI
struct ContentView: View {
@StateObject var confirmation = Confirmation()
var body: some View {
VStack {
Button(action: { confirmation.request() }) {
Text("Let‘s do this")
}
.buttonStyle(BorderedButtonStyle())
}
.alert(
"Confirm",
isPresented: $confirmation.requested,
actions: {
Button(action: { confirmation.approved = false }) {
Text("Cancel")
}
Button(action: { confirmation.approved = true }) {
Text("Confirm")
}
},
message: {
Text("Are you sure you want to do this?")
}
)
.padding()
}
}
#Preview {
ContentView()
}
@MainActor class Confirmation: ObservableObject {
@Published var requested: Bool = false
@Published var approved: Bool = false
func request() {
Task {
// Confirmation is pending
approved = false
// Update UI to prompt user
requested = true
// Await the next value which will be supplied by user action
var iterator = $approved.values.dropFirst().makeAsyncIterator()
_ = await iterator.next()
// The user took action
print(approved ? "Confirmed" : "Cancelled")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment