我收到此THREAD错误Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeecc0bfe8)
。
根据我在Example.App
中配置启动的方式,控制台将显示no pending snapshot found
或UIApplicationAdaptor does not conform to AppDelegate
。
以下是Xcode 12的代码(直接来自Firebase的Peter Friese,将Colors
替换为Example
作为应用名称)
import SwiftUI
import Firebase
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
print("Example application is starting up. ApplicationDelegate didFinishLaunchingWithOptions.")
return true
}
}
@main
struct ExampleApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
InitialView()
.environmentObject(SessionStore())
}
}
}
我的InitialView
看起来像这样:
import SwiftUI
struct InitialView: View {
@EnvironmentObject var session: SessionStore
func listen() {
session.listenAuthenticationState()
}
var body: some View {
Group {
if session.isLoggedIn {
MainView()
}
if !session.isLoggedIn {
SignInView()
}
}
.onAppear(perform: listen)
}
}
我的SessionStore
就是这样
import Foundation
import Combine
import Firebase
class SessionStore: ObservableObject {
@Published var isLoggedIn = false
var userSession: User?
var handle: AuthStateDidChangeListenerHandle?
func listenAuthenticationState() {
handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
if let user = user {
print(user.email ?? "")
let firestoreUserId = Ref.FIRESTORE_DOCUMENT_USERID(userId: user.uid)
firestoreUserId.getDocument { (document, error) in
if let dict = document?.data() {
guard let decodeUser = try? User.init(fromDictionary: dict) else { return }
self.userSession = decodeUser
}
}
self.isLoggedIn = true
} else {
print("isLoggedIn is false")
self.isLoggedIn = false
self.userSession = nil
}
})
}
}
已更新
// Firestore
static var FIRESTORE_ROOT = Firestore.firestore()
// Firestore - Users
static var FIRESTORE_COLLECTION_USERS = FIRESTORE_ROOT.collection("users")
static func FIRESTORE_DOCUMENT_USERID(userId: String) -> DocumentReference {
return FIRESTORE_COLLECTION_USERS.document(userId)
}