LoginSignup
2
2

SwiftUIでFirebaseAuthenticationを使用したログイン機能作成

Posted at

こんにちは。今回はFirebaseAuthenticationを使用して、ログイン機能を作成するやり方について書いていきたいと思います。

Firebaseの設定について

まず初めにプロジェクト作成の手順から


名前はプロジェクト名前なんかを書いたほうが分かりやすくていいと思います


アナリティクスに関しては無料で使用でき、優れているので導入するのをオススメします


アナリティクスのアカウントは元から用意されてあるものを選択してください

これでFirebaseのプロジェクトは完成したと思います。
次に、FirebaseAuthenticationの設定をします

始めるをクリックすると下記にログインで使用する機能が並んでいるので、この中から、「apple,Google,メール・パスワード」を有効にしてください。

それぞれ参考にしたサイトがあるので下記のサイトを見て導入をしてみてください
https://tech.amefure.com/swift-firebase-authentication-apple
https://tech.amefure.com/swift-firebase-authentication-google

上記と違う点はSPM(Swift Package Manager)で導入している点です。
Firebaseのドキュメント詳しく導入が書かれているので参考までに置いておきます
https://firebase.google.com/docs/ios/swift-package-manager?hl=ja

実際のコード

  • 実際にコードを書いていきますが認証部分だけ書きますのでそれ以外の部分は今回省略させていただきます

メールアドレス・パスワード編

Auth.auth().signIn(withEmail: email, password: password) { authResult, error in
guard let user = authResult?.user else {
return
if let error = error as NSError?, let errorCode = AuthErrorCode.Code(rawValue: error._code) {
                                        switch errorCode {
                                        case .invalidEmail:
                                            
                                            ""
                                        case .weakPassword:
                                            
                                            ""
                                        case .wrongPassword:
                                            
                                            ""
                                        case .userNotFound:
                                           
                                            ""
                                        case .networkError:
                                            
                                            ""
                                        default:
                                            
                                            print("default")
                                        }
                                    }
                                }
                                
                                print("サインイン成功")
                            }

新規登録編

Auth.auth().createUser(withEmail: email, password: password) { authResult, error in
                            guard let user = authResult?.user else {
                                return
                                
                                if let error = error as NSError?, let errorCode = AuthErrorCode.Code(rawValue: error._code) {
                                    switch errorCode {
                                    case .invalidEmail:
                                        
                                        ""
                                    case .weakPassword:
                                        
                                        ""
                                    case .emailAlreadyInUse:
                                        
                                        ""
                                    case .networkError:
                                        
                                        ""
                                    default:
                                        
                                        print("エラー")
                                    }
                                }
                            }
                            
                            print("サインアップ成功")
                        }

アカウント削除編

let user = Auth.auth().currentUser
                        user?.delete { error in
                            if let error {
                                print("削除できませんでした")
                            } else {
                                print("削除しました")
                            }
                        }

Googleアカウントログイン編

let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
        guard let rootViewController = windowScene?.windows.first!.rootViewController! else { return }

        guard let clientID = FirebaseApp.app()?.options.clientID else { return }

        let config = GIDConfiguration(clientID: clientID)

        GIDSignIn.sharedInstance.configuration = config

        GIDSignIn.sharedInstance.signIn(
            withPresenting: rootViewController)
        { signInResult, _ in
            guard let result = signInResult else {
                
		print("Googleアカウントエラー")
                return
            }
            
            print("Googleアカウントでのサインイン成功")
        }

注意点

Google Signinはversion7.0.0になってから書き方にアップデートがあったため、上記のように書く必要があるそうです。変更点としては、GIDSignIn.sharedInstance.signIn( withPresenting: rootViewController)の部分です。
withPresentingのみ引数に来るのでconfigは別で使用するとのこと
自分はここで大きくつまづいたので誰かの役にたればと思い、追記させていただきました。
詳しい内容は下記に書いてあります
https://github.com/WesCSK/SwiftUI-Firebase-Authenticate-Using-Google-Sign-In/blob/starting/README.md#updated-steps-for-v700-of-google-signin

SignIn with Apple編

AppleでのLoginにつきましては下記を参考にして書いたので、下記を参考に進めてみてください
https://tech.amefure.com/swift-firebase-authentication-apple

今回は自分の開発でFirebaseでのログイン機能を作っていた際につまづいた点などあったので、アウトプットも含めて記事を書きました。特にGoogleアカウントでのログイン実装の際にアップデートが入っていたため、苦戦しました。少しでも参考になれたらと思います。

2
2
0

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
2
2