たろすの技術メモ

Jot Down the Tech

ソフトウェアエンジニアのメモ書き

Failed to get FirebaseApp instance. Please call FirebaseApp.configure() before using Firestoreのエラーを解消

※この記事は[Swift5][Firestore]'Failed to get FirebaseApp instance. Please call FirebaseApp.configure() before using Firestore'のエラーを解消 - Qiitaの記事をエクスポートしたものです。内容が古くなっている可能性があります。

はじめに

iOSアプリにFirestoreを導入する際に、上記のエラーが出ました。エラー内容を直訳すると「'FirebaseAppのインスタンスを取得できませんでした。 Firestoreを使用する前に,FirebaseApp.configure()をコールしてください。」です。 自分が解消できた方法を共有します。

間違ったコード

// AppDelegate.swift
import UIKit
import Firebase 

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure() //ここに書いていた
        let db = Firestore.firestore()
        return true
    }

Firebase公式リファレンスのソースコードではこのような記述方法でしたが、自分のプロジェクトではエラーとなってしまいました。なぜ公式の方法でエラーになってしまったかはまだ分かっていません。

解決方法

// AppDelegate.swift
import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    override init() { //初期化メソッドを追記
            FirebaseApp.configure()
    }
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let db = Firestore.firestore()
        return true
    }