[英]How to access data in AppDelegate from ObservableObject class in SwiftUI
With the new SwiftUI Lifecycle there normally is no AppDelegate
anymore.使用新的 SwiftUI 生命周期,通常不再有
AppDelegate
。 However, in order to implement Firebase Messaging, it is recommended on the Firebase docs to implement an AppDelegate
and attach it using:但是,为了实现 Firebase 消息传递,建议在 Firebase 文档上实现
AppDelegate
并使用以下方法附加它:
@main
struct ExampleApp: SwiftUI.App {
// register app delegate for Firebase setup
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate //<--- HERE
@StateObject var appState = AppState()
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(appState)
}
}
}
Inside this AppDelegate
functions one obtains an FCM Token, with which the device is identified to subsequently send it notifications remotely.在这个
AppDelegate
函数中,人们获得了一个 FCM 令牌,通过该令牌可以识别设备,以便随后向其远程发送通知。 This token has to get sent to the server.此令牌必须发送到服务器。 This could be done inside the respective function inside the
AppDelegate
.这可以在
AppDelegate
内的相应 function 内完成。 However, there is a class AppState
(ObservableObject protocol) that handles the user data and writing to the server, so it would make a lot more sense to write pass it to this class (or retrieve in the class from the AppDelegate
?) and then push it from there.但是,有一个 class
AppState
(ObservableObject 协议)处理用户数据并写入服务器,因此将它写入传递给这个 class(或从AppDelegate
检索 class ?)然后然后从那里推动它。
How can this be accomplished?如何做到这一点?
edit: I guess this could be achieved by using a static
property in the AppDelegate
as described in this answer .编辑:我想这可以通过在
AppDelegate
中使用static
属性来实现,如本答案中所述。 Is using statics to access variables globally not bad practice?使用静态变量全局访问变量不是坏习惯吗? Is there a other (better) way?
还有其他(更好)的方法吗?
You can do it with the "old way" of accessing the delegate
您可以使用访问
delegate
的“旧方法”来完成
@MainActor //Required by the app delegate
class AppState: ObservableObject{
lazy var appDelegate: AppDelegate? = {
UIApplication.shared.delegate as? AppDelegate
}()
}
Then you can just use然后你就可以使用
appDelegate?.yourToken
yourToken
referencing a property in the delegate
yourToken
引用delegate
中的属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.