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

老子叫甜甜 提交于 2019-12-24 06:47:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/40334055/how-to-check-if-a-user-is-logged-in-and-if-not-redirect-to-the-login-screen

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!