gpt4 book ai didi

SwiftUI 线程 1 : Fatal error: No ObservableObject of type SessionStore found

转载 作者:行者123 更新时间:2023-12-05 09:34:45 26 4
gpt4 key购买 nike

我正在创建一个 SwiftUI 应用程序,其中包含 Firebase 以启用登录帐户,非常简单。但是当我运行这段代码时,出现以下错误“SwiftUI 线程 1: fatal error :未找到 SessionStore 类型的 ObservableObject。”调用session.session时弹出,能告诉我这段代码哪里出错了吗?谢谢大家

import UIKit
import SwiftUI
import Firebase
import Combine

struct ContentView: View {

@EnvironmentObject var session: SessionStore

func getUser () {
session.listen()
}

var body: some View{
VStack {
if session.session != nil {
LoginView()
}
else{
TabView {
ProfilView()
.tabItem {
Label("Profil", systemImage: "person")
}

NotificationsView()
.tabItem {
Label("Notifications", systemImage: "bell")
}
}
}
}
.onAppear(perform: getUser)
}
}

struct ContentView_Previews: PreviewProvider {

static var previews: some View {
ContentView().environmentObject(SessionStore())
}
}


这里是 SessionStore 模型:


import Combine
import Foundation
import Firebase

final class User {
@Published var uid: String
// var email: String?
@Published var displayName: String?

init(uid: String, displayName: String?) {
self.uid = uid
// self.email = email
self.displayName = displayName
}

}

final class SessionStore: ObservableObject {

@Published var session: User?
@Published var handle: AuthStateDidChangeListenerHandle?

func listen () {
// monitor authentication changes using firebase
handle = Auth.auth().addStateDidChangeListener { (auth, user) in
if let user = user {
// if we have a user, create a new user model
print("Got user: \(user)")
self.session = User(
uid: user.uid,
displayName: user.displayName
)
} else {
// if we don't have a user, set our session to nil
self.session = nil
}
}
}
}

最佳答案

无论在何处实例化 ContentView,都需要包含 .environmentObject(SessionStore()):

ContentView().environmentObject(SessionStore())

这需要在使用 ContentView 的任何地方发生(例如在预览和实际的应用程序层次结构本身,例如来自 SceneDelegateWindowGroup 如果您使用的是 SwiftUI View 生命周期)。

关于SwiftUI 线程 1 : Fatal error: No ObservableObject of type SessionStore found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66322124/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com