ios - 如何从 Appdelegate 显示 UIAlertController

标签 ios objective-c iphone swift3 uialertcontroller

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

我在 AppDelegate 中尝试以下代码:

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

但 UIAlertcontroller 显示在 Root View (第一个屏幕)中,对于其他 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 及以上

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/

关于ios - 如何从 Appdelegate 显示 UIAlertController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36155769/

相关文章:

iOS Swift - CoreBluetooth 无法发送数据

ios - 无法弹出 UIImagePickerController

iphone - MKMapView 上的图像标记

iphone - 核心数据关系 : How to insert a new object into an entity and create a relationship to an existing object in another entity

ios - en0 会一直是 iOS 设备上的 Wi-Fi 吗?

iphone - 如何在iPod后台添加更多自定义控件?

ios - 使用 XML 或 JSON 解析器在 iOS 应用程序中解析数据

python - iOS分块上传

ios - 退出 viewController 时停止调用 textFieldDidEndEditing

iphone - 如何将 IBAction 事件与图像相关联?