What is the best way to check if a UIAlertController is already presenting?

后端 未结 13 2095
后悔当初
后悔当初 2020-12-04 17:26

I have a tableview which, when loaded, each cell could possibly return an NSError, which I have chosen to display in a UIAlertController. Problem is I get this error in the

13条回答
  •  没有蜡笔的小新
    2020-12-04 17:46

    Well, the suggested solutions above has an essential problem from my point of view:

    If you ask your ViewController, whether the attribute 'presentedViewController' is nil and the answer is false, you can't come to the conclusion, that your UIAlertController is already presented. It could be any presented ViewController, e.g. a popOver. So my suggestion to surely check, whether the Alert is already on the screen is the following (cast the presentedViewController as a UIAlertController):

    if self.presentedViewController == nil {
       // do your presentation of the UIAlertController
       // ...
    } else {
       // either the Alert is already presented, or any other view controller
       // is active (e.g. a PopOver)
       // ...
    
       let thePresentedVC : UIViewController? = self.presentedViewController as UIViewController?
    
       if thePresentedVC != nil {
          if let thePresentedVCAsAlertController : UIAlertController = thePresentedVC as? UIAlertController {
             // nothing to do , AlertController already active
             // ...
             print("Alert not necessary, already on the screen !")
    
          } else {
             // there is another ViewController presented
             // but it is not an UIAlertController, so do 
             // your UIAlertController-Presentation with 
             // this (presented) ViewController
             // ...
             thePresentedVC!.presentViewController(...)
    
             print("Alert comes up via another presented VC, e.g. a PopOver")
          }
      }
    

    }

提交回复
热议问题