How to check if a user is logged in and if not redirect to the login screen
ios, swift2
Solution
Since you are creating your `LoginViewController` programatically so I assume that the `TabBarController` would be the `rootViewController` of the `storyboard` by default. All you need to do in your `AppDelegate` is this.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let token = UserDefaults.standard.object(forKey: "token")
if token == nil {
//***************
//Create your LoginViewController and make it the rootViewController
//***************
}
return true
}
Note: I'm using `Swift 3` so there will be a slight difference in the syntax.
Problem
I have my login screen embedded in a `UINavigationController` and my home page screen embedded in a `UITabBarController`. My login page was done programmatically and `TabBarController` was created using `storyboards`. In `AppDelegate.swift` file I made the the login screen the `rootViewController`. But now I want to check if the user is logged in and make the `TabBarController` the `rootViewController`, and if the user isn't logged in, redirect to the login screen, then segue to the `TabBarController` and make it the `rootViewController`. The server authenticates the user by sending a token to the client. Do I store the token using `NSUserDefaults`? Should I check if the user has `_token`_ as a way to validate if the user is logged in?