How to Solve Error: whose view is not in the window hierarchy

Scenario: when the mode jumps, the prompt box uialertcontroller will not appear when it is written in viewdidload, and the following warning will appear:

Solution:

You can put this code into viewdidappearance, but I think it’s better for you to get the current controller

 UIAlertController *alert = [UIAlertController alertControllerWithTitle:"Warning" message:@"sdsdfsdf" preferredStyle:  UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
        UIViewController *topRootViewController = [[UIApplication  sharedApplication] keyWindow].rootViewController;
        
        // loop
        while (topRootViewController.presentedViewController)
        {
            
            topRootViewController = topRootViewController.presentedViewController;
        }
        // Then the present operation is performed
        [topRootViewController presentViewController:alert animated:true completion:nil];

This will do

Similar Posts: