从AppDelegate展示UIAlertController

Sat*_*tre 34 objective-c ios appdelegate uialertcontroller

我正试图UIAlertController在我的iOS应用程序中呈现AppDelegate.以下是警报和本方法.

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

//Configure alert and actions

[self.window.rootViewController presentViewController:alert animated:TRUE completion:nil];
Run Code Online (Sandbox Code Playgroud)

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

Warning: Attempt to present <UIAlertController: 0x145f5d60> on <UINavigationController: 0x146590f0> whose view is not in the window hierarchy!
Run Code Online (Sandbox Code Playgroud)

导致错误的原因是什么?如何解决?

Adi*_*kar 28

如果你想从didFinishLaunchingWithOptions.Hope启动它,你也可以使用这个代码.

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)
        })
Run Code Online (Sandbox Code Playgroud)


Sre*_*nth 20

试试这个代码..

-(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]; 
}
Run Code Online (Sandbox Code Playgroud)


小智 13

最好使用类似的东西:

var hostVC = self.window?.rootViewController

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

hostVC?.presentViewController(alertController, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

如果您已经提供模态视图控制器,则以前的答案将不起作用.


Dai*_*jan 5

你在窗口启动之前调用它并且实际显示了navigationController:

"警告:尝试在窗口层次结构中显示其视图!"

你是否可以在applicationDidFinishLaunching中这样做?


等等......当视图真正出现时就像这样做

要么

一个'hack'就是强迫自己查看和窗口:

[self.window addSubview:self.rootViewController.view];
[self.window makeKeyAndVisible];
Run Code Online (Sandbox Code Playgroud)