Panda
Panda

Reputation: 6896

Checking NSUserDefaults before view is shown

Currently, I have 2 UIViews - Login View and User Profile View.

I would check if the user is logged in the Login View using viewDidLoad(). If yes, it will open User Profile View.


However, if a user is logged in, this method would open Login View for about 1s before going to User Profile View.

Is there a better method to check if user logged in, before deciding which screen to open?


Storyboard

Image


Code

override func viewDidLoad() {
    let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
    if (isLoggedIn == 1) {
        self.performSegueWithIdentifier("goto_userprofile", sender: self)
    }
    super.viewDidLoad()
}

Upvotes: 0

Views: 117

Answers (1)

Ryan Tobin
Ryan Tobin

Reputation: 224

You need to check in the application didFinishLaunchingWithOptions as opposed to viewDidLoad() to prevent the flashing of the login screen.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

    NSString *board = @"your storyboard file name"
    NSString *identifier;
    NSString *user = [[NSUserDefaults standardUserDefaults] valueForKey:@"your key"];

    if(user != nil){
        identifier = @"profile";
        //User is logged in. Go to profile page
    }
    else
        identifier = @"login";
        //User is not logged in. Go to login page

    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:board bundle:nil];

    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:identifier];

    [UIApplication sharedApplication].applicationIconBadgeNumber=10;
    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];

    return YES;
}

After implementing this code in your AppDelegate file, you need to open your storyboard file in interface builder.

enter image description here

You need to locate this above in the identity inspector. On your login view controller set the Storyboard ID to login. Set the profile View Controller Storyboard ID to profile. Once again, sorry this is in Objective-C, but I hope this helps!

Upvotes: 1

Related Questions