-1

I'm looking to show an Alert without needing to press a button, i.e. programmatically. In Swift 5 / SwiftUI in 2022.

Searching has shown me this

let alert = UIAlertController(title: "alert", message: "message", preferredStyle: UIAlertController.Style.alert)

self.present(alert, animated: true, completion: nil)

When trying the above code it has issue with the nil in the completion block, but when changing it to curlys it says the view file doesn't have present. Looks to not be for SwiftUI.

How can I show an Alert in Swift 5/SwiftUI without needing a button press?

lando2319
  • 1,509
  • 1
  • 19
  • 27
  • In SwiftUI, you can have a dedicated view model, with a published var that triggers the .alert() modifiers in the views. The problem is when you have other modal views already open: SwiftUI has issues dismissing overlapping modal views. – HunterLion Apr 30 '22 at 23:47

1 Answers1

-1

Following this Link I was able to get the following code working

struct ContentView: View {
    // pass this var as binding to other views
    @State var showAlert = false
    
    func notificationReminder() -> Alert {
            Alert(
                title: Text("Notifications Required"),
                message: Text("Please authorize notifications by going to Settings > Notifications > Remindr"),
                dismissButton: .default(Text("Okay")))
    }
    
    var body: some View {
        
        VStack {
            Text("this is my main view")
        }
        .alert(isPresented: self.$showAlert,
               content: { self.notificationReminder() })
        
    }
    
}

using code I then flipped showAlert

lando2319
  • 1,509
  • 1
  • 19
  • 27