Alexander Theißen
Alexander Theißen

Reputation: 3889

Presenting a modal view controller when loading another ViewController

Before the user can use my application he has to login. After he logged in, the database is built because I need information from the server to build it.

Therefore my root ViewController is the LoginViewController which presents the actual application (a navigationController stack) modally on successful login.

If the user is already logged in on application launch (I am storing the credentials with NSUserDefaults) the LoginViewController should present the application immediately. Therefore I overwrote the method:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    NSInteger userId = [[NSUserDefaults standardUserDefaults] integerForKey:@"selfUser"];
    if (userId != 0) {
        //[self performSelector:@selector(presentMainViewController) withObject:nil afterDelay:2];
        [self presentMainViewController];
    }
}
- (void)presentMainViewController {
    mainViewController = [[MainViewController alloc] init];
    mainViewController.managedObjectContext = managedObjectContext;
    navigationController = [[UINavigationController alloc] initWithRootViewController:mainViewController];
    navigationController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:navigationController animated:NO];
}

The [self presentMainViewController]; is executed but the controller does not show up. If I use the line above it does work.

Where do I have to put the code to make it work?

Upvotes: 4

Views: 4710

Answers (2)

Stuck
Stuck

Reputation: 12292

The view stack might not be completely created when viewDidAppear is send. So you should use the perfomSelector:withDelay to queue the call on the run loop. In this way you can ensure that the view stack is build when your code runs.

Cheers!

Upvotes: 4

nnahum
nnahum

Reputation: 364

I had a similar situation and I resolved by moving the code to viewWillAppear (instead of viewDidAppear). It may worth to try.

Upvotes: 0

Related Questions