20180626 初回起動時のみチュートリアルを出す方法

今起業と並行してiPhoneアプリを開発している。 一緒にやっているメンバーがかなり能力の高いエンジニアなので、いろいろと吸収できる。

ここでは、彼から学んでいることを吸収したり、いろいろと調べてみたけどあまりいい記事がないものを中心に記録を残しておこうと思う。

記念すべき第1回は、ちょうど昨夜話のあがった「初回起動時だけチュートリアルを出す」機能について。

ぼくのやり方は、AppDelegate.swiftの

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        return true
    }

の部分に以下のように追記した。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

  /* 初めて起動したときだけの処理 */
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let viewController:UIViewController
        
        //launchedBeforeというkeyを持っているか否かで真偽値を設定
        let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
        
        if launchedBefore == true { //初回起動時ではない場合
            viewController = storyboard.instantiateViewController(withIdentifier: "DefaultFirstView") as! ViewController
            window?.rootViewController = viewController
        } else { //初回起動時の場合の処理
            viewController = storyboard.instantiateViewController(withIdentifier: "TutorialOnlyForThefirstTime") as! TutorialViewController
            window?.rootViewController = viewController
            
            //次からlaunchedbefore == true
            UserDefaults.standard.set(true, forKey: "launchedBefore")
        }

        return true
    }

コードの流れとしては、launchedBeforeというフラグを持っていればViewControllerへ、launchedBeforeを持っていなければTutorialViewControllerへ、という内容である。

ただ、ここで一つ問題が生じてしまった。 全体でNavigationControllerを使っているのだが、初回起動時とそれ以外でrootのViewControllerが変更になるからか、NavigationBarが消えてしまうという事態が生じてしまった・・・ (これは2018年6月26日現在も未解決・・・誰か分かる人いたら教えてください・・・)

そこで、CTO(ぼくの中での呼び名。うちの会社にまだCTOはいない・・)はこのように対応してくれた。

// チュートリアル
    var isShowTutorial = true
    
    //起動時の処理
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if UserDefaults.standard.object(forKey: "isShowTutorial") != nil {
            isShowTutorial = UserDefaults.standard.object(forKey: "isShowTutorial") as! Bool
        }
        
        // チュートリアルを出す
        if isShowTutorial {
            performSegue(withIdentifier: "goTutorial", sender: nil)
            isShowTutorial = false
            UserDefaults.standard.set(isShowTutorial, forKey: "isShowTutorial")
        }

present modallyを使用して画面を遷移。 Userdefaultsの使い方がいまいちわかってないかも・・・ とりあえず反芻するためにコード部分だけ残しておこう。

頑張らねば・・・