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];
Swift 3及以上
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)
func showAlertFromAppDelegates(){
let alertVC = UIAlertController(title: "Oops" , message: "Presented Alert from AppDelegates", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.cancel) { (alert) in
exit(0) // Your code here
}
alertVC.addAction(okAction)
DispatchQueue.main.async {
var presentVC = self.window?.rootViewController
while let next = presentVC?.presentedViewController {
presentVC = next
}
presentVC?.present(alertVC, animated: true, completion: nil)
}
}
7条答案
按热度按时间bpsygsoo1#
试试这个
Objective-C
Swift 3及以上
详细说明:http://www.thecave.com/2015/09/28/how-to-present-an-alert-view-using-uialertcontroller-when-you-dont-have-a-view-controller/
8mmmxcuj2#
最短和最简单:
创建扩展名:
然后在任何地方使用
使用此选项,您可以在任何地方显示警报或任何内容示例:
替代方法:
不需要创建任何扩展或任何方法或任何东西,只需编写上述3行用于创建警报和呈现用途:
就是这样!=)
gwbalxhn3#
Anbu.Karthik's answer但是在Swift 4中。1
感谢您阅读本文。
li9yvcax4#
Swift 4.1可以使用以下代码从AppDelegate呈现alert
dnph8jn45#
为了方便起见,我使用了类别
UIAlertController+UIWindow。h
UIAlertController+UIWindow。m
用途:
8yparm6h6#
我写了一个静态类,使代码在swift 4中可重用,这个类提供了不同的方法来显示警报。
y3bcpkx17#
iOS 13及以上
自iOS 13及更高版本以来,引入了SceneDelegate来处理UI相关的生命周期。现在,Apps UI的每个示例都由UIScene表示。因此,UIWindow在Appdelegate中不再可用。
我们如何在收到远程通知时显示警报?
这样我们就可以做到这一点。