Get notified when UIAlertController is being dismissed on button press

Viewed 2564

I would like to do some actions and present some UI right before and right after any UIAlertController dismisses itself (animation is finished) due to user tapping one of the alert's buttons.

How can I get notified that user pressed some button in my UIAlertController and it is going to be dismissed and then is dismissed?

In docs it is advised against subclassing UIAlertController. I still have tried my luck subclassing, thinking that maybe it internally calls func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) on itself. Something like self.dismiss(..., but it doesn't seem to be the case on iOS10.

I have also tried to add 'manual' dismissing into UIAlertAction handler:

let alert = UIAlertController.init(...
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
    alert.dismiss(animated: true, completion: { 
        print("Dismissed")
    })
})
alert.addAction(defaultAction)

But it seems that alert is dismissed after button press but before calling handler. Anyhow it doesn't work as well. Even if it worked it would be a bit bothersome to remember to add my code into each and every UIAlertAction handler.

I would appreciate any ideas.

2 Answers

You can disable the closing animation altogether like this:

class InstantCloseAlertController: UIAlertController {
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        UIView.setAnimationsEnabled(false)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        UIView.setAnimationsEnabled(true)
    }
}

This will trigger the action handler instantly.

But I'm also currently working on exactly what you're asking (keeping the animation). I got it all sorted out but needs some more work. It involves lot's of hacking, haha. I'll post it when it's done.

Related