【Swift】UserDefaultでMainStoryBoardを分岐

 

解説

 

UserDefaultsのbool値でStoryBoardを分岐。

 

AppDelegate.swiftのdidFinishLaunchingWithOptions内に記述。

 

今回だと、

  • true : Main.storyboard
  • false : test.storyboard

のそれぞれに分岐。

 

FirebaseやNiftyCloudでログイン/ログアウトした際に、true/falseに変えるなどすれば、初期画面を分岐できる。

(初めてなら新規登録画面、利用者ならホーム画面に遷移するなど。)

 

ud.boolの初期値はfalse。

 

ストーリーボード

 

f:id:nekokichi_yos2:20190105202243p:plain

 

ソースコード

 

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        
        //UserDefaultとログイン状態を初期化
        let ud = UserDefaults.standard
        let isLogin = ud.bool(forKey: "LoginStatus")
        //ud.set(true, forKey:"LoginStatus")でboolを任意にセット可能
        
        //ログイン中ならMain.storyBoardに遷移
        if isLogin == true {
            //windowを宣言
            self.window = UIWindow(frame: UIScreen.main.bounds)
            //storyboardを宣言
            let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
            //rootViewControllerを宣言
            let rootViewController = storyboard.instantiateViewController(withIdentifier: "branch")
            //windowのrootviewcontrollerを設定
            self.window?.rootViewController = rootViewController
            //windowの背景を白にする
            self.window?.backgroundColor = UIColor.white
            //遷移
            self.window?.makeKeyAndVisible()
        //ログイン中ならtest.storyBoardに遷移
        } else {
            self.window = UIWindow(frame: UIScreen.main.bounds)
            let storyboard = UIStoryboard(name: "test", bundle: Bundle.main)
            let rootViewController = storyboard.instantiateViewController(withIdentifier: "test")
            self.window?.rootViewController = rootViewController
            self.window?.backgroundColor = UIColor.white
            self.window?.makeKeyAndVisible()
        }
        
        return true
    }