Programmatically set rootViewcontroller for UINavigationcontroller in Storyboard in Appdelegate

Aswathy Bose picture Aswathy Bose · Dec 26, 2013 · Viewed 44.3k times · Source

I have a value in NSUserdefaults. I am using storyboard, it is embedded in UINavigationController.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     if([[NSUserDefaults standardUserDefaults]objectForKey:@"isLoggedIn"]){
         //show home page here
        }else{
           // show login view
        }
}

I can open the app using a URL also

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
         NSString *text = [[url host] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

         if(text.length > 0){
           // show home page 

         }else {
          // show settings page
        }

        return YES;
}

How can I set the rootViewController for the UINavigationController based on the value that is retrieved .Can anyone please help me out?

Answer

dispatchMain picture dispatchMain · Dec 26, 2013

You can create an object of UINavigationController with your ViewController as per if/else condition and set the navigation controller as rootViewController property of window in AppDelegate as follows:

LoginViewController *loginController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"loginController"]; //or the homeController
UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:loginController];
self.window.rootViewController = navController;