Search code examples
swiftuialertcontrollerviewdidload

Function after presenting Alert Swift


TLDR
Is there a way to be notified before a UIAlert is going to be presented. Is there a viewDidLoad/viewWillLoad type function that can be called in a ViewController either before or after an alert pops up?

My Problem
My View Controller is receiving an alert from a method in my app delegate. My View Controller calls a method in the app delegate which can then send a UIAlert if there was a problem. While this seems like bad design, I can't change it. I need some type of way of knowing that an alert showed up.


Solution

  • You can try

    // do before 
    self.present(alert,animated:true) {
        // do after
    }
    

    Sol1:

    Add a completion block when you call the Appdelegate func and inside app delegate return that completion like code above in // do after

    Sol2:

    set a delegate between app delegate and the VC that calls it

    Sol3:

    use

     NotificationCenter.default.addObserver(
            self,
            selector: #selector(listenForNotification),
            name: Notification.Name(rawValue: "AlertShowed"),
            object: nil)
    

    inside the VC

    and this in Appdelagete alert completion

     NotificationCenter.default.post(name: Notification.Name("AlertShowed"), object:"")