【发布时间】:2023-03-04 23:56:01
【问题描述】:
我的视图中有一个@ObservedObject:
struct HomeView: View {
@ObservedObject var station = Station()
var body: some View {
Text(self.station.status)
}
根据来自Station.status 的String 更新文本:
class Station: ObservableObject {
@Published var status: String = UserDefaults.standard.string(forKey: "status") ?? "OFFLINE" {
didSet {
UserDefaults.standard.set(status, forKey: "status")
}
}
但是,我需要在我的AppDelegate 中更改status 的值,因为这是我收到Firebase Cloud Messages 的地方:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// Print full message.
let rawType = userInfo["type"]
// CHANGE VALUE OF status HERE
}
但是,如果我更改 AppDelegate 中的 status UserDefaults 值 - 我认为它不会更新。
当status 更改时,如何通知我在我看来的@ObservedObject?
编辑:忘了提到上述示例中使用了 SwiftUI 的 2.0 beta 版本。
【问题讨论】: