Rockers23 Rockers23 - 6 months ago 311
Objective-C Question

How to show UIAlertController from Appdelegate

I'm working with PushNotification on iOS app. I would like to show a UIalertcontroller when the app receive a notification.

I try this code below in the AppDelegate:

[self.window.rootViewController presentViewController:alert animated:YES completion:nil];


But the UIAlertcontroller is showing in the root View (First screen) and for other uiviewcontroller i got warning or the app crashes.

Answer

try this

Objective-C

UIWindow* topWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
topWindow.rootViewController = [UIViewController new];
topWindow.windowLevel = UIWindowLevelAlert + 1;

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"APNS" message:@"received Notification" preferredStyle:UIAlertControllerStyleAlert];

[alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK",@"confirm") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  // continue your work

// important to hide the window after work completed.
// this also keeps a reference to the window until the action is invoked.
topWindow.hidden = YES;
}]];

[topWindow makeKeyAndVisible];
[topWindow.rootViewController presentViewController:alert animated:YES completion:nil];

Swift

var topWindow: UIWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
topWindow.rootViewController = UIViewController()
topWindow.windowLevel = UIWindowLevelAlert + 1
var alert: UIAlertController =  UIAlertController.alertControllerWithTitle("APNS", message: "received Notification", preferredStyle: .Alert)
alert.addAction(UIAlertAction.actionWithTitle(NSLocalizedString("OK", "confirm"), style: .Cancel, handler: {(action: UIAlertAction) -> Void in
// continue your work
// important to hide the window after work completed.
// this also keeps a reference to the window until the action is invoked.
topWindow.hidden = true
}))
topWindow.makeKeyAndVisible()
topWindow.rootViewController.presentViewController(alert, animated: true, completion: { _ in })

Detail description: http://www.thecave.com/2015/09/28/how-to-present-an-alert-view-using-uialertcontroller-when-you-dont-have-a-view-controller/