我在我的视图中有一个@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 云消息 的地方:
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
中更改了UserDefaults
的status
值,它不会在我的视图中更新。
当status
发生变化时,我的视图中的@ObservedObject
如何被通知?
编辑:忘记提到该示例中使用了SwiftUI的2.0 beta版本。
@ObservedObject var station: Station
声明,因此当您创建视图时,将向其传递站点。假设您使用相同的站点对象设置状态,则视图应正确更新。 - samwize