简体   繁体   中英

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?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM