0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swift Firebaseを使いながらログイン画面を作成してみました!

Posted at

今回は、SwiftとFirebaseを使って、シンプルなログイン画面を作る手順をまとめました。Firebase Authenticationを使うと、メール・パスワードでのログイン機能を簡単に実装できます!

まずFirebaseの導入方法は、こちらで書いているのでぜひ参考にしてみてください!

Firebaseの導入したら...

ログイン画面の作成

SwiftUIで簡単なログイン画面を作ります。

import SwiftUI
import FirebaseAuth

struct LoginView: View {
    @State private var email = ""
    @State private var password = ""
    @State private var errorMessage = ""
    @State private var isLoggedIn = false

    var body: some View {
        NavigationStack {
            VStack(spacing: 20) {
                TextField("Email", text: $email)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .autocapitalization(.none)

                SecureField("Password", text: $password)
                    .textFieldStyle(RoundedBorderTextFieldStyle())

                Button("ログイン") {
                    login()
                }
                .padding()
                .background(Color.blue)
                .foregroundColor(.white)
                .cornerRadius(8)

                if !errorMessage.isEmpty {
                    Text(errorMessage)
                        .foregroundColor(.red)
                }

                NavigationLink(destination: Text("ホーム画面"), isActive: $isLoggedIn) {
                    EmptyView()
                }
            }
            .padding()
        }
    }

    func login() {
        Auth.auth().signIn(withEmail: email, password: password) { result, error in
            if let error = error {
                errorMessage = error.localizedDescription
            } else {
                isLoggedIn = true
            }
        }
    }
}

注意: 今回は1つのファイルにまとめて書きましたが、実際のアプリではアカウント登録やログアウト機能なども追加する必要があります。その場合は、処理をViewModelに分けて実装すると管理しやすくなります。

ポイント解説

  • @Stateで値を管理
    emailやpasswordの入力内容、ログイン状態など、UIに直接影響する値を管理しています。

  • Firebaseでログイン
    Auth.auth().signInを使うだけで、複雑な認証処理をFirebaseに任せられます。

まとめ

SwiftUI + Firebaseを使えば、メール・パスワードによるログイン画面はシンプルに実装できます。そして、次のステップとして、サインアップ機能やログアウト機能を追加すると、より実用的なアプリになります。

以上、Firebaseを使いながらログイン画面を作成してみました!ぜひ参考にしてみてください!🙌

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?