I'm trying to use the UserDefaults to persistently save a boolean value. This is my code :
public static var isOffline = UserDefaults.standard.bool(forKey: "isOffline") {
didSet {
print("Saving isOffline flag which is now \(isOffline)")
UserDefaults.standard.set(isOffline, forKey: "isOffline")
UserDefaults.standard.synchronize()
}
}
Why doesn't work? What is the problem in this code?
The problem is that when I try to retrieve "isOffline"
key from UserDefaults
I always get a false
.
I set the isOffline in the .onChange method of the row (I'm using Eureka as framework to create forms). The flag keep the right value during the lifecycle of the app, but when I close it that value is probably removed in some way.
synchronize()
every time you change a value in the user defaults – only when you specifically need the system to save the user defaults immediately (e.g when your app is about to be terminated) – see this Q&A. – GallicanisOffline
? – Gallicanprint
statement is successfully printing out true when you update the value? Are you updating the value for the "isOffline" key anywhere else in your app? Although note that I would agree with Venkat's suggestion of using a computed property for this, as a stored property won't be updated if the user default for "isOffline" is changed from elsewhere in your program – although that doesn't explain why your current code is failing to save values. – GallicanUserDefaults
, and it was fixable by rebootingmac os
. Maybe that's the case? #37824690 – Huysmans