【发布时间】:2021-01-04 15:51:37
【问题描述】:
我正在用 SwiftUI 编写一个应用程序并使用 Firebase 作为我的后端。
我有一个可用的首选项面板,它由应用程序本身内的一个模式组成,但我想利用 macOS 的一致首选项窗口,其中包括菜单选项以及this 文章中所写的快捷方式。
这是我的应用声明和委托。
@main
struct SchedulerApp: App {
#if os(macOS)
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#else
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#endif
@StateObject var authState = AuthState()
@StateObject var model = Model()
var body: some Scene {
WindowGroup {
ContentView()
.frame(minWidth: 800, minHeight: 450)
.environmentObject(model)
.environmentObject(authState)
}
.commands {
SidebarCommands()
}
#if os(macOS)
Settings {
Preferences()
}
#endif
}
}
#if os(macOS)
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillFinishLaunching(_ notification: Notification) {
FirebaseApp.configure()
}
}
#else
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
return true
}
}
#endif
您可以看到,我有一个委托和一个状态对象,一个对象监听身份验证状态,另一个对象保存用户数据和设置:
class AuthState: ObservableObject {
var handle: AuthStateDidChangeListenerHandle?
@Published var signedIn: Bool? = nil
init() {
listen()
}
func listen() {
Auth.auth().addStateDidChangeListener { [self] (auth, user) in
switch user == nil {
case true: signedIn = false
case false: signedIn = true
}
}
}
}
但是,当我运行此代码时,出现以下错误:
尚未配置默认 Firebase 应用。将
[FIRApp configure];(Swift 中的FirebaseApp.configure())添加到您的应用程序初始化中。阅读更多:(...)
必须先配置默认 FIRApp 实例,然后才能初始化默认 FIRAuthinstance。确保这一点的一种方法是在 App Delegate 的
application:didFinishLaunchingWithOptions:(Swift 中为application(_:didFinishLaunchingWithOptions:))中调用[FIRApp configure];(Swift 中为FirebaseApp.configure())。
我需要应用程序在初始化步骤有一个单一的事实来源 - 但由于某种原因 applicationWillFinishLaunching 在 StateObject 调用之后调用。
我的应用目前在 ContentView 中声明了这些 StateObject 类,这可以避免这些错误,但正如我上面提到的,我需要偏好来共享单一的事实来源。
非常感谢任何帮助!
【问题讨论】:
标签: ios swift firebase swiftui appdelegate