如何从 appDelegate 呈现 UIAlertView

How to present UIAlertView from appDelegate

我正在尝试从 appDelegate 中显示一个 UIAlertView didReceiveRemoteNotification 当应用收到推送通知时。

我遇到了这个错误:

  Warning: Attempt to present <UIAlertController: 0x14c5494c0> on <UINavigationController:
  0x14c60ce00> whose view is not in the window hierarchy!

这是我的代码:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: NSDictionary) {

    var contentPush: NSDictionary = userInfo.objectForKey("aps") as NSDictionary

    var message = contentPush.objectForKey("alert") as String



    let alertController = UIAlertController(title: "Default Style", message: message, preferredStyle: .Alert)

    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
                    // ...
    }
    alertController.addAction(cancelAction)

    let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in

        let photoPushedVc = self.storyboard.instantiateViewControllerWithIdentifier("CommentTableViewController") as CommentTableViewController

        println("the fetched post is \(post)")

        photoPushedVc.post = post

        let activeVc = UIApplication.sharedApplication().keyWindow?.rootViewController

        activeVc?.presentViewController(photoPushedVc, animated: true, completion: nil)
   }

   alertController.addAction(OKAction)

   let activeVc = UIApplication.sharedApplication().keyWindow?.rootViewController


   activeVc?.presentViewController(alertController, animated: true, completion: nil)}

好的,我终于明白了,在尝试显示您的 alertController 之前,您需要找到活动的 VC 使用它:

let navigationController = application.windows[0].rootViewController as UINavigationController
let activeViewCont = navigationController.visibleViewController
activeViewCont.presentViewController(alertController, animated: true, completion: nil)

我是怎么做到的

func showAlertAppDelegate(title : String,message : String,buttonTitle : String,window: UIWindow){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.Default, handler: nil))
    window.rootViewController?.presentViewController(alert, animated: true, completion: nil)
}

使用示例

self.showAlertAppDelegate(title: "Alert",message: "Opened From AppDelegate",buttonTitle: "ok",window: self.window!);

Download Example With Source Code

如果您需要 Objective-c

UIAlertController *alertvc = [UIAlertController alertControllerWithTitle:@"Alert Title..!!" message:@"Hey! Alert body come here." preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

}];

[alertvc addAction:actionOk];
  1. 如果您有基于导航的应用程序:

    UINavigationController *nvc = (UINavigationController *)[[application windows] objectAtIndex:0].rootViewController;
    UIViewController *vc = nvc.visibleViewController;
    [vc presentViewController:alertvc animated:YES completion:nil];
    
  2. 如果您有基于单一视图的应用程序:

    UIViewController *vc = self.window.rootViewController;
    [vc presentViewController:alertvc animated:YES completion:nil];
    

使用Objective-CAppDelegate生成AlertController对话框,

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Hello World!" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];

类型 1

UIWindow *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
alertWindow.rootViewController = [[UIViewController alloc] init];
alertWindow.windowLevel = UIWindowLevelAlert + 1;
[alertWindow makeKeyAndVisible];
[alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];

类型 2

UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topController.presentedViewController) {
    topController = topController.presentedViewController;
}
[topController presentViewController:alertController animated:YES completion:nil];

两者都经过测试并且工作正常。

在应用程序委托的顶部控制器上显示警报

var topController : UIViewController = (application.keyWindow?.rootViewController)!

    while ((topController.presentedViewController) != nil) {
        topController = topController.presentedViewController!
    }

    //showAlertInViewController func is in UIAlertController Extension
    UIAlertController.showAlertInViewController(topController, withMessage: messageString, title: titleString)

在 UIAlertController 中添加扩展

    static func showAlertInViewController(viewController: UIViewController?, withMessage message: String, title: String) {
    let myAlert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

    myAlert.addAction(UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .Default, handler: { (action: UIAlertAction!) in
        print("Handle Ok logic here")

        // Let the alert simply dismiss for now
    }))

    viewController?.presentViewController(myAlert, animated: true, completion: nil)
}

这是我的Swift 3.0 示例

func showTopLevelAlert() {
    let alertController = UIAlertController (title: "title", message: "message.", preferredStyle: .alert)

    let firstAction = UIAlertAction(title: "First", style: .default, handler: nil)
    alertController.addAction(firstAction)

    let cancelAction = UIAlertAction(title: "Отмена", style: .cancel, handler: nil)
    alertController.addAction(cancelAction)

    let alertWindow = UIWindow(frame: UIScreen.main.bounds)

    alertWindow.rootViewController = UIViewController()
    alertWindow.windowLevel = UIWindowLevelAlert + 1;
    alertWindow.makeKeyAndVisible()

    alertWindow.rootViewController?.present(alertController, animated: true, completion: nil)

}

希望对大家有所帮助

我使用 UIViewController 扩展来获取当前可见视图控制器(参见:How to get visible viewController from app delegate when using storyboard?)。

然后呈现警报控制器:

let visibleVC = UIApplication.sharedApplication().keyWindow?.rootViewController?.visibleViewController
visibleVC!.presentViewController(alertController, animated: true, completion: nil)