简体   繁体   中英

IOS: Code to present login screen modally

I want to password protect app with login screen (and join screen for first use). Some answers on SO suggest testing if user is logged in in viewdidappear of initial screen and, if not logged in, presenting the login screen modally.

I tried this but code is not working. Does anyone know up to date code for presenting a modal view controller? Note I created login screen in storyboard and have given it storyboard id "login".

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //if not logged in, modally present login screen here.

    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"loggedIn"]) {
        // go to login screen
        NSLog(@"not logged in");//this fires so logic is ok
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UIViewController *ivc = [storyboard instantiateViewControllerWithIdentifier:@"login"];//this line gives warning it is not being used
    } else {
        // go to main screen
    }
} 
/*perhaps I should call this somewhere?

- (void)presentModalViewController:(UIViewController *)modalViewController animated:(BOOL)animated
*/

Credit to @rdelmar comment, You have to presentViewController:animated:completion: (presentModalViewController:animated: that ivc.

- (void)viewDidAppear:(BOOL)animated
{
   [super viewDidAppear:animated];
   //if not logged in, modally present login screen here.

   if(![[NSUserDefaults standardUserDefaults] boolForKey:@"loggedIn"]) {
       // go to login screen
       NSLog(@"not logged in");//this fires so logic is ok
       UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
       UIViewController *ivc = [storyboard instantiateViewControllerWithIdentifier:@"login"];//LOOK AT NEXT LINE
       [self presentViewController:ivc animated:YES completion:nil]; //THIS LINE IS MISSING.
  } else {
    // go to main screen
  }
}

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