gpt4 book ai didi

ios - 如何从 Appdelegate 显示 UIAlertController

转载 作者:IT王子 更新时间:2023-10-29 07:52:10 26 4
gpt4 key购买 nike

我正在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com