Search code examples
iosuinavigationcontrollersegueappdelegatexcode-storyboard

Instantiate view controller from within navigation stack on launch


I have an app like this

Navigation controller -> login controller -> main view controller -> other stuff

I want to try to login in applicationdidfinishloadingwithoptions, and if that is successful then load main view controller, otherwise load the login view controller. My problem is I want the navigation stack to remain intact like above no matter what, so that I can pop back to my login view controller if I want to log out.

Right now I try to instantiate a main view controller on successful login, but on logout and other navigations it complains that I don't have a navigation controller embedded.

What is the correct way to do this?


Solution

  • If you are using storyboards then first of all create a UIViewController for Login and give it a storyboard ID, second create your mainViewController and embed it in UINavigationController and give storyboard id to UINavigationController.

    After that in AppDelegate.m's applicationdidfinishloadingwithoptions load your appropriate VC based on user is logged in OR not.

    Example

    // Check if user is logged in
    if ([[NSUserDefaults standardUserDefaults] stringForKey:@"loggedIn"] == NULL || [[[NSUserDefaults standardUserDefaults] stringForKey:@"loggedIn"] isEqualToString:@"false"]) {
            // show login page
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
            UIViewController *mainViewController = [storyboard instantiateViewControllerWithIdentifier:@"login"];
    
            self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            self.window.rootViewController = mainViewController;
            [self.window makeKeyAndVisible];
    } else {
    
            // show home page
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *mainViewController = [storyboard instantiateViewControllerWithIdentifier:@"home"];
    
            self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
            self.window.rootViewController = mainViewController;
            [self.window makeKeyAndVisible];
    }
    

    Edit

    So your stack will become like this

    NavController->mainVC->OtherStuff
    

    And standalone

    LoginVC