带Firebase和Xcode 12的SwiftUI应用生命周期

时间:2020-11-11 06:00:41

标签: firebase google-cloud-firestore swiftui ios14 xcode12

我收到此THREAD错误Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeecc0bfe8)

根据我在Example.App中配置启动的方式,控制台将显示no pending snapshot foundUIApplicationAdaptor does not conform to AppDelegate

以下是Xcode 12的代码(直接来自Firebase的Peter Friese,将Colors替换为Example作为应用名称)

https://medium.com/firebase-developers/firebase-and-the-new-swiftui-2-application-life-cycle-e568c9f744e9


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)
    }

0 个答案:

没有答案