如何从Appdelegate显示UIAlertController

我正在iOS应用上使用PushNotification。 我想在应用程序收到通知时显示一个UIalertcontroller。

我在AppDelegate下面试试这个代码:

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

但UIAlertcontroller显示在根视图(第一屏幕)和其他uiviewcontroller我得到警告或应用程序崩溃。

尝试这个

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]; 

Swift3

 let topWindow = UIWindow(frame: UIScreen.main.bounds) topWindow.rootViewController = UIViewController() topWindow.windowLevel = UIWindowLevelAlert + 1 let alert = UIAlertController(title: "APNS", message: "received Notification", preferredStyle: .alert) alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "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.isHidden = true })) topWindow.makeKeyAndVisible() topWindow.rootViewController?.present(alert, animated: true, completion: { _ in }) 

迅速

 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 }) 

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