user3808557
user3808557

Reputation: 61

Change Initial View Controller for First Launch

I know this question has been asked but the methods are not working for me. I have a view controller that contains a tutorial, which I only want to display as the initial view the first time the app is opened. After that, the main menu will always be the initial view. The storyboard ID for my Tutorial screen is "Tutorial". I have the following code to detect first launch, but I can't figure out how to make the tutorial appear:

  - (void)viewDidLoad
 {
if ([[NSUserDefaults standardUserDefaults]boolForKey: @"FirstLaunch"])
{}
else{

    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"FirstLaunch"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

Upvotes: 2

Views: 2150

Answers (1)

Artem Loginov
Artem Loginov

Reputation: 801

You can change initial controller in two ways:

  1. Check 'Is Initial VC' checkbox at Interface Builder or
  2. Configure it at -application:didFinishLaunchingWithOptions: method

Changing initial view controller using Application Delegate

In -application:didFinishLaunchingWithOptions: in your application delegate (AppDelegate.m) add if/else to check the necessity of tutorial:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    if (![[NSUserDefaults standardUserDefaults] boolForKey: @"FirstLaunch"])
    {
       [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"FirstLaunch"];
       [[NSUserDefaults standardUserDefaults] synchronize];
       /*** load vc ***/
    }
    return YES;
} 

To set the initial controller you have to initialize window property, create vc and set it as root:

// 1. Initialize window
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
// 2. Get storyboard
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
// 3. Create vc
TutorialViewController *tutorialViewController = [storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([TutorialViewController class])];
// 4. Set as root
self.window.rootViewController = tutorialViewController;
// 5. Call to show views
[self.window makeKeyAndVisible];

Hope it helps!

Upvotes: 3

Related Questions