firebase - 如何通过读取环境对象来纠正此问题?(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
}
}
在此先感谢您的帮助,我真的很感激,所以谢谢!!!!
解决方案
您必须将该userInfo
变量实际传递到您的视图层次结构中,以便它对 InitialView 及其子项可见:
@ObservedObject var userInfo = UserInfo()
var body: some Scene {
WindowGroup {
InitialView()
.environmentObject(userInfo)
}
}
environmentObject
无论您使用的是 SwiftUI 生命周期还是SceneDelegate
. 更多阅读environmentObject
:https ://www.hackingwithswift.com/quick-start/swiftui/how-to-use-environmentobject-to-share-data-between-views
您可以选择是否声明userInfo
为 anObservedObject
或StateObject
可能取决于您的操作系统目标版本:SwiftUI 中 ObservedObject 和 StateObject 之间的区别是什么
推荐阅读
- jenkins - 强制 UTF8 环境变量 Jenkins
- python - 由于数据长度不等,将嵌套 JSON 列表展平为 Pandas DataFrame 的问题
- python - 字典只返回部分答案(也许是关于缩进)
- c++ - 提升范围和 ADL 查找导致不明确的调用
- url - 屏蔽敏感的 url 查询参数
- ios - 从另一个类swift调用文本字段
- mysql - 从mysql获取数据,耗时近436秒
- ffmpeg - ffmpeg 在一个步骤中淡入动画和徽标覆盖
- javascript - 使用url的Angularjs下载功能
- http - PUT 和 POST 有什么区别,为什么 PUT 被认为是幂等的?