LoginSignup
12
14

More than 3 years have passed since last update.

[Swift/FirebaseAuth] 一度ログインしたらログイン画面をスキップする方法

Last updated at Posted at 2021-02-26

Firebase Authentication を使ってユーザーの認証を行うアプリを作る際、一度新規登録・ログインをしたら次アプリを開くときログイン画面をスキップしてくれるコードを紹介します。

この記事ではすでに FirebaseAuth を使って新規登録・ログイン画面と処理が完成してることを前提とします。これらのやり方は Firebase Official Docが丁寧に説明してくれてるので参考にしてください!

Code

この処理は SceneDelegate.swift で行います。
まず FirebaseAuth ライブラリをインポートします。

SceneDelegate.swift
import FirebaseAuth

SceneDelegate クラスの中に以下のメソッドを書きます。

SceneDelegate.swift
    func skipLogin() {
         //使ってるストーリーボード(何もいじってない限り ファイル名は"Main.storyboard" なので "Main" と記入。
         let storyboard = UIStoryboard(name: "Main", bundle: nil)

         //ログイン後に飛びたいストーリボード。Identifier は Main.storyboard で設定。
         let homeViewController = storyboard.instantiateViewController(identifier: "HomeVC")

         //rootViewController (初期画面)を homeViewController にする。
         window?.rootViewController = homeViewController

         //画面を表示。
         window?.makeKeyAndVisible()
     }

ちなみに storyboard ID はここで設定します。
スクリーンショット 2021-02-26 午後4.01.11.png

skipLogin()メソッドが書き終わったらあとは次のメソッドの中に呼ぶだけです!

SceneDelegate.swift
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }

        -----ここから付け足す-----
        //もし一度ログインしたユーザーだったら skipLogin() を呼ぶ。
        if Auth.auth().currentUser != nil {
           skipLogin()
        }
        //rootController がデフォルトで新規登録・ログイン画面についていれば else文はいらない。
    }

これで、一度ログインしたら次からログイン画面をスキップできるようになります!

12
14
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14