user3497437 user3497437 - 1 year ago 78
iOS Question

How to check if a user is logged in and if not redirect to the login screen.

Hello i have my login screen embedded in a navigation controller and my home page screen embedded in a Tab controller. My login page was done programmatically and Tab Controller 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 TabController the rootview controller, and the if user isn't logged in, redirect to the login screen, then segue to the Tab controller and make it the rootview. The server authenticates the user by sending a token to the client. Do i store the token using NSDefault()? Should i check if the user has token as a way to validate if the user is logged in.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download