如何从 Appdelegate 显示 UIAlertController [英] How to show UIAlertController from Appdelegate

查看:26
本文介绍了如何从 Appdelegate 显示 UIAlertController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 iOS 应用上使用 PushNotification.我想在应用收到通知时显示 UIalertcontroller.

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

我在 AppDelegate 中尝试以下代码:

I try this code below in the AppDelegate:

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

但是 UIAlertcontroller 显示在根视图(第一个屏幕)中,对于其他 uiviewcontroller,我收到警告或应用程序崩溃.

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

推荐答案

试试这个

目标 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; // if you want to hide the topwindow then use this
    topWindow = nil; // if you want to remove the topwindow then use this 
}]];

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

Swift3 及以上

var topWindow: UIWindow? = UIWindow(frame: UIScreen.main.bounds)
topWindow?.rootViewController = UIViewController()
topWindow?.windowLevel = UIWindow.Level.alert + 1

let alert = UIAlertController(title: "APNS", message: "received Notification", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel) { _ 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 // if you want to hide the topwindow then use this
    topWindow = nil // if you want to hide the topwindow then use this
 })

topWindow?.makeKeyAndVisible()
topWindow?.rootViewController?.present(alert, animated: true, completion: nil)

详细说明:http://www.thecave.com/2015/09/28/how-to-present-an-alert-view-using-uialertcontroller-when-you-没有视图控制器/

这篇关于如何从 Appdelegate 显示 UIAlertController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆