Search code examples
iosuinavigationcontrolleruiwindowappdelegate

UIWindow loses rootviewcontroller after launch


My application has a UIWindow with a correctly set rootview controller. I know this because I check for the rootViewController after it is set (in the app delegate), and all is well.

Once My app launches, everything works fine. My issue is that the rootview controller is no longer set correctly on the UIWindow when I check in the 'main' view.

My app works fine.. so what is the issue you may be wondering... well, I am trying to implement AdColony (video advertising), an they need to grab the UIWindow's rotviewcontroller to dislplay their ad. When they check for the rootviewcontroller... it is null.

I have added code to check as well.. and the rootviewcontroller is null.

How can my UIWindow lose its pointer to the rootviewcontroller? I need help understanding how the UIWindow architecture works.

Thanks

code that checks for UIWindow's visible controller (the below code returns nil for the viewcontrollers value.

    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    UIViewController* rootViewController = [window rootViewController];

    [self getVisibleViewControllerChild:rootViewController];


- (UIViewController*)getVisibleViewControllerChild:(UIViewController*)viewController {

UIViewController* visibleViewController = nil;

if(!viewController) {
    NSLog(@"nil");
    return nil;
}

if ([viewController isKindOfClass:[UINavigationController class]]) {
    UINavigationController* navigationController = (UINavigationController*)viewController;
    viewController = navigationController.visibleViewController;
    NSLog(@"viewcontroller is nav controller");
}

while (visibleViewController == nil) {

    if (viewController.modalViewController == nil) {
        visibleViewController = viewController;
        NSLog(@"visibleViewController = %@", visibleViewController);
    } else {

        if ([viewController.modalViewController isKindOfClass:[UINavigationController class]]) {
            UINavigationController *navigationController = (UINavigationController *)viewController.modalViewController;
            viewController = navigationController.visibleViewController;
            NSLog(@"modal 1");
        } else {
            viewController = viewController.modalViewController;
            NSLog(@"modal 2");
        }
    }

}

return visibleViewController;

}


Solution

  • I can't really figure out what you're trying to do with this code, but the method keyWindow seems to be returning nil, so rootViewController will also be nil. I'm not sure why that's true, but you can get the rootViewController with (I assume you're doing this from a view controller):

    self.view.window.rootViewController