Anthony Anthony - 5 months ago 25
iOS Question

How hide UIAlertControllers globally in the app when app enters in backround

I need a system to hide all

UIAlertController
in my app when she enters in background. Currently I use a
BaseViewController
class for all my
UIViewControllers
that register to "enter background" notification and has a reference to a
UIAlertViewController
. This
BaseViewController
hides the popup if it appears visible. It works but it is not practical.

An other way is subclassing but Apple doc say :


The UIAlertController class is intended to be used as-is and does not
support subclassing. The view hierarchy for this class is private and
must not be modified.


Do you have a better solution that does not involve subclassing the
UIViewController
who contains the
UIAlertController
?

Answer

plz use this code you need to get top view controller

use this method to get top view controller

    -(id)getTopViewController{


           UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

            while (topController.presentedViewController) {
                topController = topController.presentedViewController;
            }
            if (![topController isKindOfClass:[NSNull class]]) {

                return topController;
            }



    }


  - (void)applicationDidEnterBackground:(NSNotification *)notification
    {

      UIViewController *viewOb = [self getTopViewController];

   // check  UIViewController is  UIAlertController
    if ([view isKindOfClass:[UIAlertController class]]) {
         NSLog(@"%@",view);
     [viewOb dismissViewControllerAnimated:YES completion:nil];

    }


   }

then dismissViewController with top viewController