Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get storyboard-defined UINavigationController from AppDelegate

In storyboard, I have an introductory view controller which fades to a UINavigationController.

      |   |      |   |
   -> |   |  ->  |   |     
      |   |      |   |
     ViewCtrl   NavCtrl

I would like to get a reference to the navigation controller from the app delegate (like the @Guillaume answer does in this question).

Here's how I'm trying to access it:

UIApplication.sharedApplication.delegate.window.rootViewController.navigationController;

But the navigation controller is nil.

Any notion why the navController is nil or what I can do to get a reference to it?

like image 491
bbrame Avatar asked Aug 22 '13 19:08

bbrame


2 Answers

UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                                         bundle: nil];

UINavigationController *controller = (UINavigationController*)[mainStoryboard 
                    instantiateViewControllerWithIdentifier: @"<Controller ID>"];

You specify the controller identifier for your navigation controller in the attributes inspector of the navigation controller.

like image 69
Arsen Avatar answered Oct 21 '22 14:10

Arsen


So Arsen's solution looks nice but I didnt know how to get the name of my storyboard lol. What worked for me was

UINavigationController *navigationController = (UINavigationController*)_window.rootViewController;
AVDashboardViewController *dashBoardViewController =
(AVDashboardViewController*)[navigationController.viewControllers  objectAtIndex:1];//since on index 0 I have my login screen and index 1 is the home screen

Getting the NavigationController's reference on the AppDelegate might seem like bad coding practice, but in my case I needed it because it is where the

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 

is located, which is one of the methods called when a Notification is received. I also struggled on how to update the navigation controller once I got the message, so maybe off topic but here is a free tip:

UIBarButtonItem *notiButton = [[UIBarButtonItem alloc] initWithTitle: @"Received push!" style: UIBarButtonItemStyleBordered target:self action:nil];

[[dashBoardViewController navigationItem] setLeftBarButtonItem:notiButton animated:YES];

[navigationController popToViewController:dashBoardViewController animated:YES];

Hope it helps!

like image 27
Stenio Ferreira Avatar answered Oct 21 '22 13:10

Stenio Ferreira