首页 > 解决方案 > I want to set a view controller as initial view controller

问题描述

When user is already logged In then the app should be open from home page and he/she should not go to the login page again.

I have tried this code it shows no error but it is not working.

let token = UserDefaults.standard.string(forKey: "token")  ?? ""
if !token.isEmpty
{
   let storyboard = UIStoryboard(name: "Main", bundle: nil)
   let firstVC = 
                storyboard.instantiateViewController(withIdentifier: 
                "initController") as! ViewController
   self.window?.rootViewController = firstVC
   self.window?.makeKeyAndVisible()
 }

I expect that when user is already logged In then when she again open the app he/she must directly go the home page and should not go again to the login page.

标签: swift4

解决方案


let token = UserDefaults.standard.string(forKey: "token") ?? ""
if !token.isEmpty
 {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window = UIWindow(frame: UIScreen.main.bounds)
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let yourVC = mainStoryboard.instantiateViewController(withIdentifier: 
                     "initController") as! HomeController
    appDelegate.window?.rootViewController = yourVC
    appDelegate.window?.makeKeyAndVisible()
    super.viewDidLoad()
  }

推荐阅读