如何解决带Firebase和Xcode 12的SwiftUI应用生命周期
我收到此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)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。