在我正在开发的应用程序中,我需要在应用程序启动时根据用户是否登录显示不同的 View Controller
- 如果用户已经登录,我需要显示
HomeViewController
- 如果用户没有登录,我需要显示
LoginViewController
目前,我的编码方式如下-
AppDelegate
的window
的rootViewController
始终嵌入UINavigationController 中的
.LoginViewController
在
LoginViewController
的viewDidAppear
方法中,我检查用户是否已登录。如果是,则推送HomeViewController
.在
<HomeViewController
中,当用户注销时,我弹出HomeViewController
以显示LoginViewController
有更好的方法吗?
最佳答案
哪种方法更好,完全取决于您的要求和 self 满意度。
现在考虑一下您的方法:
- If you're going with this approach then login screen will display for fraction of time. If it is okay for you then you can for it.
现在想想我的方法:
- I think the better way is to check the same condition in
didFinishLaunchingWithOptions
instead ofloginVC
- If you are going this approach then your HomeVC is directly displayed after your splash screen. It is the main advantage of this approach
代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let isLoggedIn = true
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let navigationController = storyboard.instantiateViewController(withIdentifier: "NavigationController") as! UINavigationController
var viewController:UIViewController
if !isLoggedIn{
viewController = storyboard.instantiateViewController(withIdentifier: "LoginVC")
}else{
viewController = storyboard.instantiateViewController(withIdentifier: "HomeVC")
}
navigationController.viewControllers = [viewController]
window?.rootViewController = navigationController
return true
}
Anbu.Karthik 更新:
只需在 AppDelegate.swift
文件中定义方法,然后在需要时调用它。此外,示例代码中也实现了相同的方法。
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.logoutFromApp()
更改 Root View Controller 的代码:
func logoutFromApp(){
guard let rootNavigationController = window?.rootViewController as? UINavigationController else {
return
}
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "LoginVC")
rootNavigationController.viewControllers = [viewController]
}
关于ios - 如何根据用户是否登录来处理在应用程序启动时显示不同的 View Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56455249/