背景信息
我已经开始为一个简单的应用程序开发后端,并且我已经设置了一个数据库类(名为 DBDelegate
),所有文件都将与之通信。
在我的 AppDelegate.swift
中我有这个:
static public var dbDelegate:DBDelegate = DBDelegate()
private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
return true
}
它是一个static public
,所以我可以从其他文件访问dbDelegate
。
在我的其他文件中,我有以下内容来帮助提高可读性:(因为它是一个类,它将通过引用传递)
let dbDelegate = AppDelegate.dbDelegate
在我的 DBDelegate
类中:
var db = Firestore.firestore()
init() {
FirebaseApp.configure()
}
构建和运行
当我构建我的代码时,它构建得很好。
在运行时,应用程序立即崩溃并显示 SIGABRT
。
错误信息是:
由于未捕获的异常“FIRAppNotConfiguredException”而终止应用程序,原因:“无法获取 FirebaseApp 实例。请在使用 Firestore 之前调用 FirebaseApp.configure()'
我尝试过的
- 我试过在
DBDelegate
类的 init 函数上放置一个断点。它没有到达断点。 - 我已尝试使所有
dbDelegate
变量惰性
:- 我在 AppDelegate 中遇到一个编译错误:
lazy 不能用于已经是 lazy 的全局
- 其他人的运行时错误:请在使用 Firestore 之前调用 FirebaseApp.configure()。
- 我在 AppDelegate 中遇到一个编译错误:
- 我尝试了以下方法(在 didFinishLaunchingWithOptions 中分配 dbDelegate):
static public var dbDelegate:DBDelegate! private func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() dbDelegate = DBDelegate() return true }
- 我收到编译错误:
静态成员“dbDelegate”不能用于“AppDelegate”类型的实例
任何帮助都会很棒!
编辑:我找到了一个糟糕的解决方案,见下文。
最佳答案
首先,我要感谢@DionzB 建议使用单例(我这样做了)。我将在这个答案中引用他/她的帖子。
好的,经过一些研究和使用断点,我发现我的自定义类实际上在 AppDelegate 之前执行。知道这一点后,我在以下行之前创建了一个变量:
static let shared = FirebaseService()
名字无所谓,因为我/你不会调用,赋值给FirebaseApp.configure()
FirebaseService 类变为:
class FirebaseService: NSObject {
let constantToNeverTouch = FirebaseApp.configure()
static let shared = FirebaseService()
init() {
}
}
接下来,您必须确保 FirebaseApp.configure() 不在代码的其他位置。它也不应该在 AppDelegate 中。拥有多个 FirebaseApp.configure() 会使应用崩溃。
关于ios - 错误 : `call FirebaseApp.configure() before using Firestore` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469351/