2

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.

Matt Bart
  • 809
  • 1
  • 7
  • 26

3 Answers3

1

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:"")
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

The function present(_:animated:completion:) takes an Optional completion handler, completion. If you provide a completion handler it gets called once the modal is displayed. You display UIAlertControllers using present(_:animated:completion:), so just pass in a completion handler.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

If you are opening the alert from within a method in appdelegate, then you should some how keep a reference on your view controller and call a specific method on it before showing the alert.

Or even, you can implement a pub sub design where you’d have your controller register for a custom notification name on the Notification Center and call/post that notification from the appdelegate just before showing the alert, don’t forget about removing the observer once the controller gets closed.

The choice is yours

TheFuquan
  • 1,737
  • 16
  • 18