Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

Warning: Attempt to present <CustomViewController> on <UINavigationontroller> whose view is not in the window hierarchy

I know this has been asked a million times, but I couldn't find a suitable answer in those many questions that I've examined.

I have a custom view controller, and I'm trying to display the view controller when the user taps a button (so no "infamous viewDidLoad problem" here).

Here is my code that runs when the user taps the button: (I have the NIB for the view controller, and I have a navigation controller)

ICLoginViewController *loginViewController = [[ICLoginViewController alloc] initWithNibName:@"ICLoginViewController" bundle:[NSBundle mainBundle]];
//assuming we have a navigation controller.

UINavigationController *navigationController= (UINavigationController*)[[UIApplication sharedApplication] keyWindow].rootViewController;
[navigationController.topViewController presentViewController:loginViewController animated:YES completion:nil];

I'm getting the Warning: Attempt to present <ICLoginViewController: 0xa08a810> on <UINavigationController: 0xa45de70> whose view is not in the window hierarchy! error when I try to present the view controller. Nothing happens on screen. If I tap multiple times I get the same error, and still nothing happens. I've set a breakpoint and verified that navigationController and navigationController.topViewController are not nil. I' using storyboard (if it helps) but not for the custom view controller that I'm trying to display. (I want to make it an app-independent library in the long run, so I'm not referencing any app-specific modules within) Why am I getting this error?

Upvotes: 0

Views: 1555

Answers (2)

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

I've found the solution. The problem was, my modally displayed view controller was not the 'top' view controller in navigation controller. If I change the calling view controller to be pushed instead of being modal, then it becomes the top view controller and my app works well. Apparently, this had nothing to do with my custom view controller, but my navigation stack.

Upvotes: 1

David Wong
David Wong

Reputation: 10294

If its in an NSObject create a method inside the NSObject that takes your current viewController as an argument and present it there. eg:

-(void)presentInViewController:(UIViewController *)controller{
    ICLoginViewController *loginViewController = [[ICLoginViewController alloc] initWithNibName:@"ICLoginViewController" bundle:[NSBundle mainBundle]];
    [controller presentViewController:loginViewController animated:YES completion:^(BOOL comp){}];
}

This way you can call that view controller wherever you want instead of trying to find your way through the navigation stack from UIApplication.

Upvotes: 0

Related Questions