问题描述
我想为登录到 firebase 的应用编写一个模板,以便我可以在以后的项目中使用它。我遵循了在 YouTube 上找到的在线教程: https://www.youtube.com/watch?v=DotGrYBfCuQ&list=PLBn01m5Vbs4B79bOmI3FL_MFxjXVuDrma&index=2
所以我面临的问题是,在视频中,变量 userInfo 在 SceneDelegate 中实例化,允许 YouTube 上的编码人员在他的代码中引用 userInfo。我尝试在 AppDelegate 和 App Struct 中做同样的事情。无济于事。
这是应用程序结构中的代码:
import SwiftUI
import Firebase
@main
struct WoobApp: App {
// Adapts AppDelegate to SwiftUI
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var userInfo = UserInfo()
var body: some Scene {
WindowGroup {
InitialView()
}
}
}
class AppDelegate : NSObject,UIApplicationDelegate {
// Configure Firebase When App Launches
func application(_ application : UIApplication,didFinishLaunchingWithOptions launchOptions : [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
return true
}
}
初始视图:
struct InitialView: View {
@EnvironmentObject var userInfo : UserInfo
var body: some View {
Group {
if userInfo.isUserAuthenticated == .undefined {
UndefinedView()
}
else if userInfo.isUserAuthenticated == .signedOut {
UndefinedView()
}
else if userInfo.isUserAuthenticated == .signedIn {
UndefinedView()
}
}
.onAppear{
self.userInfo.configureFirebaseStateDidChange()
}
}
这是用户数据:
class UserInfo : ObservableObject {
enum FBAuthState {
case undefined,signedIn,signedOut
}
@Published var isUserAuthenticated : FBAuthState = .undefined
func configureFirebaseStateDidChange() {
isUserAuthenticated = .signedIn
isUserAuthenticated = .signedOut
}
}
在此先感谢您的帮助,我真的很感激,谢谢!!!
解决方法
您必须实际将该 userInfo
变量传递到您的视图层次结构中,以便它对 InitialView 及其子项可见:
@ObservedObject var userInfo = UserInfo()
var body: some Scene {
WindowGroup {
InitialView()
.environmentObject(userInfo)
}
}
无论您使用的是 SwiftUI 生命周期还是 environmentObject
,通过 SceneDelegate
传递它的原则都是正确的。有关 environmentObject
的更多阅读:https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views
您可以选择将 userInfo
声明为 ObservedObject
还是 StateObject
,这可能取决于您的操作系统目标版本:What is the difference between ObservedObject and StateObject in SwiftUI