How to display a UIAlertController from any subclass of NSObject?

I have an outdated code base that I manage, which should display warning messages from all sides. This is a terrible practice and needs a refactor, but it will not happen in the near future. With iOS 9, I need the ability to start and forget a warning view, and for me, the view and queue were displayed.

+2
ios ios9 uialertview uialertcontroller
Jul 17 '15 at 9:17
source share
3 answers

Like other people, this is usually bad practice and violates the principles of MVC. However, if you manage an outdated code base and refactoring, everything is simply not an option, I created this class that allows you to handle the UIAlertController like the old UIAlertView , it controls the display of alerts from any class, as well as the alert queue for you ...

https://github.com/sammio2/SMHAlertController

+1
Jul 17 '15 at 9:17
source share

To show UIAlertController , we need a UIViewController object. Therefore you can use below for this.

  UIWindow *keyWindow = [[UIApplication sharedApplication]keyWindow]; UIViewController *mainController = [keyWindow rootViewController]; [mainController presentViewController:alert animated:YES completion:nil]; 

thank

+6
Jul 17 '15 at 9:37
source share

To display the UIAlertController in the NSObject class, use the code below.

  UIAlertController * popup = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) { [popup dismissViewControllerAnimated:YES completion:nil]; }]; [popup addAction:cancel]; UIViewController *rootViewController = [[Helper shareInstance] topViewController]; [rootViewController presentViewController:popup animated:YES completion:nil]; 

// Put the method below in your global helper class.

  - (UIViewController *)topViewController { return [self topViewController:[UIApplication sharedApplication].keyWindow.rootViewController]; } - (UIViewController *)topViewController:(UIViewController *)rootViewController { if (rootViewController.presentedViewController == nil) { return rootViewController; } if ([rootViewController.presentedViewController isMemberOfClass:[UINavigationController class]]) { UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController; UIViewController *lastViewController = [[navigationController viewControllers] lastObject]; return [self topViewController:lastViewController]; } UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController; return [self topViewController:presentedViewController]; } 
0
Aug 24 '17 at 9:44 on
source share



All Articles