首页 > 解决方案 > 如何通过读取环境对象来纠正此问题?(SwiftUI 并且在没有 SceneDelegate 的情况下工作)

问题描述

我想为登录到 firebase 的应用程序编写一个模板,以便我可以在未来的项目中使用它。我遵循了 YouTube 上的在线教程: https ://www.youtube.com/watch?v=DotGrYBfCuQ&list=PLBn01m5Vbs4B79bOmI3FL_MFxjXVuDrma&index=2

所以我面临的问题是,在视频中,变量 userInfo 在 SceneDelegate 中被实例化,从而允许 YouTube 上的编码人员在其代码中引用 userInfo。我尝试在 AppDelegate 和 App Struct 中做同样的事情。无济于事。

这是 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
    
}
}

在此先感谢您的帮助,我真的很感激,所以谢谢!!!!

标签: firebasefirebase-authenticationswiftuiuiscenedelegate

解决方案


您必须将该userInfo变量实际传递到您的视图层次结构中,以便它对 InitialView 及其子项可见:

@ObservedObject var userInfo = UserInfo()

var body: some Scene {
    WindowGroup {
        InitialView()
          .environmentObject(userInfo)
    }
}

environmentObject无论您使用的是 SwiftUI 生命周期还是SceneDelegate. 更多阅读environmentObjecthttps ://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views

您可以选择是否声明userInfo为 anObservedObjectStateObject可能取决于您的操作系统目标版本:SwiftUI 中 ObservedObject 和 StateObject 之间的区别是什么


推荐阅读