ios 从 AppDelegate 呈现 UIAlertController

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26952061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:38:19  来源:igfitidea点击:

Present UIAlertController from AppDelegate

iosobjective-cappdelegateuialertcontroller

提问by Satre

I'm trying to present a UIAlertControllerfrom the AppDelegate in my iOS app. Below is the alert and the present method.

我正在尝试UIAlertController在我的 iOS 应用程序中呈现来自 AppDelegate 的a 。以下是警报和当前方法。

UIAlertController *alert = [UIAlertController alertControllerWithTitle:cTitle message:cMessage preferredStyle:UIAlertControllerStyleAlert];

//Configure alert and actions

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

However, when I try to present the alert, it doesn't appear and I get the following alert in the console.

但是,当我尝试显示警报时,它没有出现,我在控制台中收到以下警报。

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

What is causing the error and how do I fix it?

是什么导致了错误,我该如何解决?

回答by Aditya Gaonkar

You can use this code as well if you want to launch it from didFinishLaunchingWithOptions.Hope this helps.

如果您想从 didFinishLaunchingWithOptions 启动它,您也可以使用此代码。希望这会有所帮助。

dispatch_async(dispatch_get_main_queue(), {
              let importantAlert: UIAlertController = UIAlertController(title: "Action Sheet", message: "Hello I was presented from appdelegate ;)", preferredStyle: .ActionSheet)
            self.window?.rootViewController?.presentViewController(importantAlert, animated: true, completion: nil)
        })

回答by Sreekanth

try this code..

试试这个代码..

-(void)application:(UIApplication *)application               didReceiveLocalNotification:(UILocalNotification *)notification
{
 NSLog(@"rakshapettu");
 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"AlertView" message:@"I am an AlertView" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action) {
                                                          [alert dismissViewControllerAnimated:YES completion:nil];
                                                      }];
[alert addAction:defaultAction];
UIWindow *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
alertWindow.rootViewController = [[UIViewController alloc] init];
alertWindow.windowLevel = UIWindowLevelAlert + 1;
[alertWindow makeKeyAndVisible];
[alertWindow.rootViewController presentViewController:alert animated:YES completion:nil]; 
}

回答by Mikhail Mkl

It's better to use something like:

最好使用类似的东西:

var hostVC = self.window?.rootViewController

while let next = hostVC?.presentedViewController {
    hostVC = next
}

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

Previous answers won't work if you are already presenting modal view controller.

如果您已经在展示模态视图控制器,以前的答案将不起作用。

回答by Daij-Djan

you call it before the window is up and the navigationController is actually shown:

你在窗口打开之前调用它并且实际显示导航控制器:

"Warning: Attempt to present on whose view is not in the window hierarchy!"

“警告:尝试呈现不在窗口层次结构中的视图!”

likely you do so in applicationDidFinishLaunching?

您可能在 applicationDidFinishLaunching 中这样做吗?



EITHER wait .. like do it when the view really appears

要么等待..喜欢在视图真正出现时做

OR

或者

one 'hack' would be to force the view and window up yourself:

一个“黑客”将是强制视图并自己打开窗口:

[self.window addSubview:self.rootViewController.view];
[self.window makeKeyAndVisible];

回答by Kevin

I was trying the same but does not work because after change of viewcontroller still returned the initial viewcontroller and throw the error whose view is not in the window hierarchy!. Finally, I found the solution to this problem:

我正在尝试相同但不起作用,因为在更改视图控制器后仍然返回初始视图控制器并抛出错误whose view is not in the window hierarchy!。最后,我找到了这个问题的解决方案:

UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)

But I have to force view controllers to update de keyWindowwith this:

但是我必须强制视图控制器使用以下内容更新 de keyWindow

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    UIApplication.sharedApplication().keyWindow!.rootViewController = self
    UIApplication.sharedApplication().keyWindow!.makeKeyAndVisible()
}

回答by kakubei

You can try calling it in viewDidAppearinstead of viewDidLoad. I had a similar error and that fixed it.

您可以尝试调用它viewDidAppear而不是viewDidLoad. 我有一个类似的错误,并修复了它。

回答by A.G

Using Alert Controller:

使用警报控制器:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
dispatch_async(dispatch_get_main_queue(), {

    //INTERNET NOT AVAILABLE ALERT
    var internetUnavailableAlertController = UIAlertController (title: "Network Unavailable", message: "Please check your internet connection settings and turn on Network Connection", preferredStyle: .Alert)

    var settingsAction = UIAlertAction(title: "Settings", style: .Default) { (_) -> Void in
        let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
        if let url = settingsUrl {
            UIApplication.sharedApplication().openURL(url)
        }
    }
    var cancelAction = UIAlertAction(title: "Okay", style: .Default, handler: nil)
    internetUnavailableAlertController .addAction(settingsAction)
    internetUnavailableAlertController .addAction(cancelAction)
    self.window?.rootViewController!.presentViewController(internetUnavailableAlertController , animated: true, completion: nil)
    })

Using AlertView:

使用警报视图:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    dispatch_async(dispatch_get_main_queue(), {

        //INTERNET NOT AVAILABLE ALERTVIEW

        let internetUnavailableAlert =  UIAlertView(title: "Network Unavailable", message: "Please check your internet connection settings and turn on Network Connection", delegate: self, cancelButtonTitle: "Okay")
        internetUnavailableAlert.show()
        })

  return true
 }
}