【问题标题】:How do I correct this issue with reading an Environment Object? (SwiftUI and working without a SceneDelegate)如何通过读取环境对象来纠正此问题? (SwiftUI 并且在没有 SceneDelegate 的情况下工作)
【发布时间】:2021-01-16 20:17:53
【问题描述】:

我想为登录到 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
    
}
}

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

【问题讨论】:

    标签: firebase firebase-authentication swiftui uiscenedelegate


    【解决方案1】:

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

    @ObservedObject var userInfo = UserInfo()
    
    var body: some Scene {
        WindowGroup {
            InitialView()
              .environmentObject(userInfo)
        }
    }
    
    

    无论您使用的是 SwiftUI 生命周期还是 SceneDelegate,通过 environmentObject 传递它的原则都是正确的。更多阅读environmentObjecthttps://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views

    您可以选择是否将userInfo 声明为ObservedObjectStateObject,这可能取决于您的操作系统目标版本:What is the difference between ObservedObject and StateObject in SwiftUI

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2013-06-08
      • 2017-11-13
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多