Swift: 動態更改 initial viewcontroller

2017061515:49


App 的設計常常會有的狀況:

啟動 App 後
  已經登入 --> 直接跳掉 App主功能畫面
  尚未登入 --> 先顯示登入畫面

但 Storyboard 中已經將 Initial View Controller 指向「登入 View」時
如何在已登入狀況下,直接、馬上顯示主功能畫面?

--> 只要讓程式判斷登入與否,再決定 Initial View Controller 是哪一個!


在 AppDelegate.swft 中:


    //App啟動後 第一個呼叫的method
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        //----------------------------------------------------------------
        //判斷使否已登入
        
        let flag_login = 1;//修改這個值 以改變 init view
        
        if (flag_login == 0) { //還沒登入
           
            self.window = UIWindow(frame: UIScreen.main.bounds)
            let storyboard = UIStoryboard(name: "Main2", bundle: nil) //Storyboard的名稱
            
            let initialViewController = storyboard.instantiateViewController(withIdentifier: "view000") // view 的 ID
            
            self.window?.rootViewController = initialViewController
            self.window?.makeKeyAndVisible()
            
        } else { //已經登入
            
            
            self.window = UIWindow(frame: UIScreen.main.bounds)
            let storyboard = UIStoryboard(name: "Main", bundle: nil) //Storyboard的名稱
            
            let initialViewController = storyboard.instantiateViewController(withIdentifier: "view02") // view 的 ID
            
            self.window?.rootViewController = initialViewController
            self.window?.makeKeyAndVisible()
            
        }

            
   
        
        return true
    }



以上的相關程式:
https://github.com/hellofire/initial_vc


參考
set initial viewcontroller in appdelegate - swift
https://stackoverflow.com/questions/26753925/set-initial-viewcontroller-in-appdelegate-swift