如何检查用户是否已登录以及是否未重定向到登录屏幕 [英] How to check if a user is logged in and if not redirect to the login screen
问题描述
我的登录屏幕嵌入在UINavigationController
中,而主页屏幕嵌入在UITabBarController
中.
I have my login screen embedded in a UINavigationController
and my home page screen embedded in a UITabBarController
.
我的登录页面已通过编程方式完成,并且使用storyboards
创建了TabBarController
.在AppDelegate.swift
文件中,将登录屏幕设置为rootViewController
.
My login page was done programmatically and TabBarController
was created using storyboards
. In AppDelegate.swift
file I made the the login screen the rootViewController
.
但是现在我想检查用户是否已登录并将TabBarController
设置为rootViewController
,如果用户未登录,请重定向至登录屏幕,然后选择TabBarController
和将其设置为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
.
服务器通过向客户端发送令牌来对用户进行身份验证.我是否使用NSUserDefaults
存储令牌?我是否应该检查用户是否具有_token
_作为验证用户是否已登录的方法?
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?
推荐答案
由于您是以编程方式创建LoginViewController
的,因此我假定TabBarController
默认为storyboard
的rootViewController
.您在AppDelegate
中所需要做的就是这个.
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
}
注意:我使用的是Swift 3
,因此语法上会有细微的差别.
Note: I'm using Swift 3
so there will be a slight difference in the syntax.
这篇关于如何检查用户是否已登录以及是否未重定向到登录屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!