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

我在AppDelegate中try 以下代码:

[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; // 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 and above

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-dont-have-a-view-controller/

Objective-c相关问答推荐

按住自定义 UIButton 时更改深灰色突出显示的 colored颜色 ?

使用正则表达式搜索 NSString

将 NSNumber 转换为 NSDecimalNumber

在objective-c / cocoa-touch中是否有一个方便的功能来找到最小的数字?

增加推送通知徽章 iPhone

我可以以编程方式滚动到 UIPickerView 中所需的行吗?

如何以编程方式退出 mac 应用程序?

Objective-C 的文档生成器?

在不导入自己的情况下播放系统声音

iOS 5:对 UIAppearance 感到好奇

alloc 和 allocWithZone: 有什么区别?

将 HTTP 标头添加到 NSURLRequest

Objective-C 中的 super 到底是什么?

将块存储在数组中

如何对包含数字的 NSMutable 数组进行排序?

Modal segue,导航栏消失

AVAssetImageGenerator 提供旋转的图像

iOS 11 large-title导航栏不折叠

有没有办法在不使用 UINavigationController 的情况下更改 Storyboard 中 UINavigationBar 的高度?

字符串常量和字符串文字有什么区别?