ios - 如何根据用户是否登录来处理在应用程序启动时显示不同的 View Controller ?

标签 ios

在我正在开发的应用程序中,我需要在应用程序启动时根据用户是否登录显示不同的 View Controller

  • 如果用户已经登录,我需要显示HomeViewController
  • 如果用户没有登录,我需要显示LoginViewController

目前,我的编码方式如下-

  • AppDelegatewindowrootViewController 始终嵌入 UINavigationController 中的 LoginViewController .

  • LoginViewControllerviewDidAppear 方法中,我检查用户是否已登录。如果是,则推送 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 of loginVC
  • 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
}

Download sample code

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/

相关文章:

ios - FBSDKAppInviteDialogDelegate 的 Swift 实现不起作用

ios - 在 Xcode 上使用 Parse (Swift) 注册时出错

ios - SpriteKit 和 UIScrollView 以及 HUD

ios - 默认详细 View uisplitview

javascript - 从 iOS 到 WebSockets 的二进制数据

ios - 多重分配和零指针分配内存概念

ios - 恢复状态导航 Controller 后后退按钮标题被截断

ios - 如何在 Objective C 中检查 UIView 是否为零

iphone - iPhone 日历

ios - 尝试在 UICollectionViewCell 上设置 subview 的框架