LoginSignup
2

posted at

【Firebase・Swift】初回起動時やログイン時、新規会員登録時に表示するViewを変える

1. 初回起動時や非ログイン時に表示するためのViewControllerとstoryboardを用意する

今回はTutorialというディレクトリを作成し、その中にTutorialViewController.swiftTutorial.storyboardを作成しました
image.png
Tutorial.storyboardで、初回起動時や非ログイン時に遷移したいViewを選択し、Storyboard IDを設定します
image.png

2. SceneDelegateで最初に表示するViewを変更するコードを書く

SceneDelegate.swiftを開き、以下のコードを追記します

SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
+         Auth.auth().addStateDidChangeListener { (auth, user) in
+             if user == nil {
+                 guard let scene = (scene as? UIWindowScene) else {
+                     return
+                 }
+                 let window = UIWindow(windowScene: scene)
+                 self.window = window
+                 window.makeKeyAndVisible()
+                 
+                 let vc = UIStoryboard(name: "Tutorial", bundle: nil).instantiateViewController(withIdentifier: "TutorialView") as! TutorialViewController
+                 window.rootViewController = vc
+             }
+         }
        guard let _ = (scene as? UIWindowScene) else { return }
}

内容としては、

  • FirebaseのAuthサービスのステートリスナーを追加し、ユーザーがサインインしているかを確認する
  • ユーザーがサインインしていない場合、新しいUIWindowを作成し、それを表示する。
    StoryboardからTutorialViewControllerをインスタンス化し、それをwindowのrootViewControllerに設定する
  • ユーザーがサインインしている場合は、何もしない

を行っています

3. TutorialViewController.swiftを設定する

今回は次のようにコードを書きました

TutorialViewController.swift
import UIKit
import Firebase
import FirebaseAuthUI
import FirebaseOAuthUI
import FirebaseGoogleAuthUI

class TutorialViewController: UIViewController, FUIAuthDelegate {
    
    let authUI = FUIAuth.defaultAuthUI()!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let providers: [FUIAuthProvider] = [
            FUIGoogleAuth(authUI: authUI),
            FUIOAuth.appleAuthProvider()
        ]
        self.authUI.delegate = self
        self.authUI.providers = providers
    }
    
    @IBAction func LoginButtonTapped() {
        let authViewController = self.authUI.authViewController()
        self.present(authViewController, animated: true, completion: nil)
    }
    
    public func authUI(_ authUI: FUIAuth, didSignInWith authDataResult: AuthDataResult?, error: Error?){
        if let error = error {
            print(error)
        }

        let db = Firestore.firestore()
        let userRef = db.collection("users").document(Auth.auth().currentUser!.uid)
        userRef.getDocument { (snapshot, error) in
            print(snapshot)
            if let error = error {
                print(error)
                return
            }
            if snapshot?.exists == true {
                let mainVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HomeView") as UIViewController
                mainVC.modalPresentationStyle = .fullScreen
                mainVC.modalTransitionStyle = .crossDissolve
                self.present(mainVC, animated: true)
            } else {
                //新規会員登録画面に遷移する
            }
        }

    } 
}

内容としては、

  • viewDidLoadメソッドで、GoogleとAppleの認証プロバイダを設定し、delegateに自身を設定する
  • LoginButtonTappedアクションメソッドが呼び出されると、認証画面が表示される
  • authUI(_:didSignInWith:error:)メソッドは、認証が完了した後に呼び出され、Firestoreからユーザー情報を取得する
  • 取得したユーザー情報が存在すれば、HomeViewに遷移、存在しなければ、SignUp画面に遷移する

を行っています。

また、新規登録・ログインが完了した後に遷移したいViewのStoryboard IDを設定しておきます
image.png

これで、初回起動時やログイン時、新規会員登録時に表示するViewを変えることができます

リポジトリはこちら

ログイン機能の実装についても同じリポジトリを用いて解説しています
こちらもぜひ参考にしてください

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
What you can do with signing up
2