1

I want to open a login screen and I have tried both programmatically and both with a segue. I have seen similar questions but it didn't fix it for me.

Here are my two versions of code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (![[API sharedInstance] isAuthorized]) {
        NSLog(@"I should Open login screen");
        [self performSegueWithIdentifier:@"ShowLogin" sender:nil];
    }
}

or

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (![[API sharedInstance] isAuthorized]) {
        NSLog(@"I should Open login screen");
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    LoginScreen *vc = [sb instantiateViewControllerWithIdentifier:@"LoginScreen"];
    vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:vc animated:YES completion:NULL];
    }
}

The segue is modal style.

In both cases the NSLog is printed and then I see a warning:

Warning: Attempt to present <LoginScreen: 0x1e5bd010> on <PhotoScreen: 0x1e5b82e0> whose view is not in the window hierarchy!

and the new view does not open.

Any hint on that?

ghostrider
  • 5,131
  • 14
  • 72
  • 120

1 Answers1

2

Don't do this in viewDidLoad, your view isn't on screen yet, so that's why you get that error. You should do it in viewDidAppear (with no animation if you don't want to see the view of the controller that this code is in).

rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • However viewDidAppear will be called once again once the modal view is dismissed thus presenting the same modal again. – Steve Moser Dec 16 '13 at 17:57
  • @SteveMoser, you need to put some logic in viewDidAppear, so that it only presents it if certain conditions are met. For instance, if you only want it shown when the app is started up, you could set a flag after you do the presentation. – rdelmar Dec 16 '13 at 18:02
  • Hmm, seems less than ideal to check login state every time a modal screen is dismissed. – Steve Moser Dec 16 '13 at 18:35
  • @SteveMoser, sure, that's a good way too. I think it's mostly a coding preference thing. If I'm having a controller present another controller, I prefer to have that code in that controller's file, rather than calling it from the app delegate. – rdelmar Dec 16 '13 at 21:06