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?

【初心者向け】Firebaseでログイン機能つけてみた

Posted at

はじめに

前回、Storyboard + UIKitを使って、お天気アプリを作りました。
今回はそのアプリに**Firebase Authentication(認証)**を使って、ログイン機能を追加してみました。

Googleの提供するFirebaseを使うことで、メールアドレス+パスワードによる認証を簡単に導入できます。
初めてFirebaseを触る人でもできるよう、手順を順番にまとめています。

実装したこと

  • Firebaseのセットアップ(iOSアプリ連携)
  • メールアドレスとパスワードでのユーザー登録/ログイン
  • ログイン後に天気検索画面に遷移

使用ツール

  • Xcode(Storyboard + UIKit)
  • Firebase Authentication(メール・パスワード認証)
  • CocoaPods(Firebase SDK導入)

1. Firebaseの準備

プロジェクト作成

  1. Firebase コンソール にアクセス
  2. 新しいプロジェクトを作成
  3. iOSアプリを追加(バンドルIDを入力)

GoogleService-Info.plist の追加

  • ダウンロードした GoogleService-Info.plist をXcodeプロジェクトに追加します。

Firebase SDKの導入

CocoaPodsを使って導入します。

pod init

Podfileに以下を追加:

pod 'Firebase/Auth'

インストール:

pod install

インストール後は .xcworkspace を開いて作業します。

##AppDelegateの設定

import FirebaseCore

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        FirebaseApp.configure()
        return true
    }
}

##2. Storyboardでログイン画面を作成

以下のUIパーツをStoryboardに配置します。
• UITextField(メールアドレス用)
• UITextField(パスワード用、Secureに設定)
• UIButton(ログインボタン)
• UIButton(新規登録ボタン)
• UILabel(エラーメッセージ表示用)

ログイン成功後は、天気検索画面へSegueを使って遷移します。

##3. ログイン・新規登録のコード

import UIKit
import FirebaseAuth

class LoginViewController: UIViewController {

    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var errorLabel: UILabel!

    @IBAction func loginTapped(_ sender: UIButton) {
        guard let email = emailTextField.text,
              let password = passwordTextField.text else { return }

        Auth.auth().signIn(withEmail: email, password: password) { result, error in
            if let error = error {
                self.errorLabel.text = "ログイン失敗: \(error.localizedDescription)"
            } else {
                self.performSegue(withIdentifier: "toWeatherScreen", sender: nil)
            }
        }
    }

    @IBAction func signUpTapped(_ sender: UIButton) {
        guard let email = emailTextField.text,
              let password = passwordTextField.text else { return }

        Auth.auth().createUser(withEmail: email, password: password) { result, error in
            if let error = error {
                self.errorLabel.text = "登録失敗: \(error.localizedDescription)"
            } else {
                self.errorLabel.text = "登録成功。ログインしてください。"
            }
        }
    }
}

##4. ログイン状態を保持したまま遷移する

天気検索画面(ViewController.swift)の viewDidLoad でログイン状態をチェックします。

override func viewDidLoad() {
    super.viewDidLoad()

    if Auth.auth().currentUser == nil {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let loginVC = storyboard.instantiateViewController(withIdentifier: "LoginViewController")
        loginVC.modalPresentationStyle = .fullScreen
        present(loginVC, animated: true, completion: nil)
    }
}

##5. ハマったこと・注意点
• Firebase SDKの初期化は AppDelegate に FirebaseApp.configure() を忘れずに書く
• Firebaseに登録したバンドルIDとXcode側が一致していることを確認
• エラーメッセージが英語なので、ログを見て内容を理解することが大切
• StoryboardでSegueを使う場合は、Identifier名の打ち間違いに注意

##まとめ

Firebaseを使えば、サーバー側の実装をせずにログイン機能を簡単に追加できます。
UIKitとStoryboardだけでも十分に構築可能です。

次は、ログインしたユーザーごとにデータを保存できるよう、Firestoreとの連携にもチャレンジしてみたいです。

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?