Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode: Display Login View in applicationDidBecomeActive

In my app I would like to show a login screen - which will be displayed when the app starts and when the app becomes active. For reference, I am using storyboards, ARC and it is a tabbed bar application.

I therefore need to do the process in the applicationDidBecomeActive method:

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if ( ... ) { // if the user needs to login
        PasswordViewController *passwordView = [[PasswordViewController alloc] init];
        UIViewController *myView = self.window.rootViewController;
        [myView presentModalViewController:passwordView animated:NO];
    }
}

To an extent this does work - I can call a method in viewDidAppear which shows an alert view to allow the user to log in. However, this is undesirable and I would like to have a login text box and other ui elements. If I do not call my login method, nothing happens and the screen stays black, even though I have put a label and other elements on the view.

Does anyone know a way to resolve this? My passcode view is embedded in a Navigation Controller, but is detached from the main storyboard.

like image 268
Patrick Avatar asked Nov 22 '12 16:11

Patrick


1 Answers

A variety of answers finally led me to an answer which doesn't seem too complicated so I will post it here - and it actually looks really good if I am honest.

Firstly, my password view is embedded in a Navigation Controller (Editor -> Embed In) and this is connected to the main tab bar controller using a modal segue with an id, in my case 'loginModal'.

In the applicationDidBecomeActive method put something like this:

[self performSelector:@selector(requestPasscode) withObject:nil afterDelay:0.2f];

And then put this function somewhere in the App Delegate

-(void)requestPasscode{
    if ( /* If the user needs to login */ ) {
        [self.window.rootViewController performSegueWithIdentifier:@"loginModal" sender:self];
    }
}

This will present your login view whenever the app begins or enters the foreground (for example, when switching apps).

NOTE: The above line will not work if the root of your app is embedded in a navigation controller.

There are however two bugs;

  1. If the user was previously viewing a modal view when they dismissed the app
  2. If the user dismissed the app on the password view.

Both of these cause the app to crash so the following line goes in the applicationWillResignActive method.

[self.window.rootViewController dismissViewControllerAnimated:NO completion:nil];

It basically dismisses all modal views that are presented. This may not be ideal, but modal views are more often then not, used for data entry and so in many cases, this is a desired effect.

like image 96
Patrick Avatar answered Oct 21 '22 18:10

Patrick