Search code examples
iosswiftparse-platformxcode6usersession

how to keep current user session active using parse?


I am attempting to keep the current user session active until the user decides to log out. What code i should i implement? and exactly where should it be implemented? the viewDidLoad, or viewWillAppear function of the root view? I have tried using this code in my root view:

override func viewDidAppear(animated: Bool) {
        let vc = ViewController()
        var loggedIn = false

        if PFUser.currentUser() != nil {
            loggedIn = true
        } else {
            presentViewController(vc, animated: true, completion: nil)
        }
    }

but whenever i stop the simulator and run it again, i have to log in all over again. What is the best solution? keep in my "ViewController" is my main view which holds my login/sign up fields. So i basically want a way to say if a current user session exist, continue, else, show initial view.


Solution

  • Try this in your app delegate...

    -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    ...
    
    PFUser *currentUser = [PFUser currentUser];
    
    if (currentUser) {
      // there is a user logged in go to the main screen
        UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
        MainViewController *mainViewController = (MainViewController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"Main"];
    
        //set the root controller to it
        self.window.rootViewController = mainViewController;
    } else {
    // Log in!
        UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Login" bundle: nil];
        LoginViewController *loginViewController = (LoginViewController *)[mainStoryboard instantiateViewControllerWithIdentifier:@"Login"];
    
        //set the root controller to it
        self.window.rootViewController = loginViewController;
    }
    
    ...