Until iOS 13.4 I was using a property observer to update the UserDefaults for a @Published Bool value
@Published var mutedAudio: Bool = UserDefaults.standard.bool(forKey: "mutedAudio") {
didSet { UserDefaults.standard.set(self.mutedAudio, forKey: "mutedAudio") }
}
With the first beta of iOS 13.4 didSet() is not called anymore if I use in SwiftUI the toggle() method and I must use a logical negation:
Button(action: {
// self.settings.mutedAudio.toggle() doesn't work in iOS 13.4
self.settings.mutedAudio = !self.settings.mutedAudio // workaround
}) {
Image(systemName: settings.mutedAudio ? "speaker.slash.fill" : "speaker.2.fill").resizable().frame(width: 24, height: 24)
}
Is there a better solution than waiting for the next iOS 13.4 beta?
You can directly subscribe to mutedAudio in your init or another place, for example:
class SomeClass: ObservableObject {
var cancellable: Cancellable?
@Published var mutedAudio: Bool = UserDefaults.standard.bool(forKey: "mutedAudio")
init() {
cancelable = $mutedAudio.sink(receiveValue: { (value) in
UserDefaults.standard.set(value, forKey: "mutedAudio")
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With