How do I dismiss a rootViewController before presenting a new UITabBarController?

前端 未结 3 599
臣服心动
臣服心动 2021-01-29 06:53

I\'ve set up a UIViewController as my rootViewController in AppDelegate, however, when a user logs in or skips it I am presenting a UITabBarController over the top.

I n

3条回答
  •  隐瞒了意图╮
    2021-01-29 07:44

    It's too easy to maintain condition for user logged in or not, and then based on that status. You can navigate to your view.

    You can try this way :

    1.In AppDelegate you can these methods.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
    
        let isLogin = UserDefaults.standard.bool(forKey: "IS_LOGIN")
        if isLogin == true {
            self.goToDashboardView()
        } else {
            self.goToLoginView()
        }
        return true
    }
    
    //MARK:- ------- Global Methods -------
    
    class func sharedInstance() -> AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
    
    func goToLoginView() {
    
        let sb = UIStoryboard.init(name: "Main", bundle: nil)
        let loginVC = sb.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
        let navVC = UINavigationController(rootViewController: loginVC) // You can skip this if you do not want to add navigation bar
        self.window?.rootViewController = navVC // if you skipped above line, then you have to assign 'loginVC' here.
        self.window?.makeKeyAndVisible()
    }
    
    func goToDashboardView() {
    
        let sb = UIStoryboard.init(name: "Main", bundle: nil)
        let tabbarVC = sb.instantiateViewController(withIdentifier: "MyTabBarController") as! MyTabBarController
        self).window?.rootViewController = tabbarVC // if you skipped above line, then you have to assign 'loginVC' here.
        self.window?.makeKeyAndVisible()
    }
    

    2.In LoginViewController, when user logged in successfully.

    @IBAction func btnLoginClicked(_ sender: UIButton) {
    
        // Your API call or other code
        // If all things goes well, then login and go to dashboard
    
        UserDefaults.standard.set(true, forKey: "IS_LOGIN")
        AppDelegate.sharedInstance().goToDashboardView()
    }
    

    3.And finally, whenever and from wherever you want to log out from app, just call below code.

    @IBAction func btnLogOutClicked(_ sender: UIButton) {
    
        // Your API call or other code
        // If all things goes well, then logout and go to login view
    
        UserDefaults.standard.set(false, forKey: "IS_LOGIN")
        AppDelegate.sharedInstance().goToLoginView()
    }
    

    4.And Main.storyboard should have design something like :

提交回复
热议问题