gpt4 book ai didi

ios - 如何观察 UserDefaults 的变化?

转载 作者:行者123 更新时间:2023-12-04 16:40:05 25 4
gpt4 key购买 nike

我有一个 @ObservedObject在我看来:

struct HomeView: View {

@ObservedObject var station = Station()

var body: some View {
Text(self.station.status)
}

它基于 String 更新文本来自 Station.status :
class Station: ObservableObject {
@Published var status: String = UserDefaults.standard.string(forKey: "status") ?? "OFFLINE" {
didSet {
UserDefaults.standard.set(status, forKey: "status")
}
}
但是,我需要更改 status 的值在我的 AppDelegate ,因为那是我收到我的 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
}
但是如果我改变 status UserDefaults值在 AppDelegate - 在我看来它不会更新。
我的怎么可以 @ObservedObject在我看来 status 时会收到通知变化?
编辑:忘记提及 SwiftUI 的 2.0 测试版用于上述示例。

最佳答案

这是可能的解决方案

import Combine

// define key for observing
extension UserDefaults {
@objc dynamic var status: String {
get { string(forKey: "status") ?? "OFFLINE" }
set { setValue(newValue, forKey: "status") }
}
}

class Station: ObservableObject {
@Published var status: String = UserDefaults.standard.status {
didSet {
UserDefaults.standard.status = status
}
}

private var cancelable: AnyCancellable?
init() {
cancelable = UserDefaults.standard.publisher(for: \.status)
.sink(receiveValue: { [weak self] newValue in
guard let self = self else { return }
if newValue != self.status { // avoid cycling !!
self.status = newValue
}
})
}
}
注意:SwiftUI 2.0 允许您使用/观察 UserDefaults直接通过 AppStorage查看,因此如果您只需要查看该状态,则可以使用
struct SomeView: View {
@AppStorage("status") var status: String = "OFFLINE"
...

关于ios - 如何观察 UserDefaults 的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62713150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com