Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating a View Controller programmatically with Storyboard from AppDelegate

I'm busy building an app - that when launched for the first time it asks the user to do two things:

  1. Select a Country
  2. Accept T&Cs

From there it goes to the home view controller.

The problem I am currently facing is pushing the first view controller onto the screen from my app delegate. I'm using storyboards / Xcode 5/ iOS7

Here is the code I came up with:

UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle: nil];
BBCounterySettingsViewController *controller = (BBCounterySettingsViewController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"CountrySettings"];
[navigationController pushViewController:controller animated:NO];

The problem is the app crashes when it hits the last line of code with the following error:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIViewController pushViewController:animated:]: unrecognized selector sent to instance 0x8e9a400'

Anyone have any ideas what I am doing wrong?

like image 270
Robert J. Clegg Avatar asked Dec 12 '13 09:12

Robert J. Clegg


1 Answers

You're expecting the self.window.rootViewController to be a UINavigationController but it's a UIViewController. This means that the outermost view controller in your storyboard is of the wrong type.

A better way to obtain the UINavigationController (Which should work in this case) is to use the property self.navigationController on any UIViewController.

From what I understand you want to present a view the first time the user runs to have the user pick some stuff. What you should then do is present a modal view controller, like this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//isFirstRun is some boolean you use to determine if it's the first run
if(isFirstRun){
    BBCounterySettingsViewController *controller = (BBCounterySettingsViewController *)[mainStoryboard instantiateViewControllerWithIdentifier: @"CountrySettings"];
    [self.window.rootViewController presentViewController: controller animated:YES completion:nil];
}
like image 123
Rick Avatar answered Oct 11 '22 05:10

Rick