UserDefaults not saved using Swift 3

I am trying to use UserDefaults to persist 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 does not it work? What is the problem in this code?

EDIT: The problem is that when I try to extract a key "isOffline"from UserDefaults, I always get false.

EDIT 2: I set isOffline in the string's .onChange method (I use Eureka as a framework for creating forms). The flag maintains the correct value throughout the life cycle of the application, but when I close it, this value is probably deleted somehow.

+4
source share
2 answers

, "didSet". , userDefaults - .

Synchronize() . , , ( UserDefaults):

-synchronize NS_DEPRECATED .

, , :

public static var isOffline = UserDefaults.standard.bool(forKey: "isOffline") {
        didSet {
            print("Saving isOffline flag which is now \(isOffline)")
            DispatchQueue.main.async {
                    UserDefaults.standard.set(isOffline, forKey: "isOffline")
                }

        }
    }

- , , , .

+10

,

public static var isOffline:Bool {
    get {
       return UserDefaults.standard.bool(forKey: "isOffline")
    }
    set(newValue) {
        print("Saving isOffline flag which is now \(isOffline)")
        UserDefaults.standard.set(newValue, forKey: "isOffline")
        UserDefaults.standard.synchronize()
    }
}
+3

Source: https://habr.com/ru/post/1664684/


All Articles