Home > database >  Obtain User Defaults in Different ViewController
Obtain User Defaults in Different ViewController

Time:11-13

I have my user defaults defined as follow in ViewControllerSettings
public let kAlertsKey = "ALERTS_KEY"
And it is modified through a switch and an ìf statement with the following code

if switchAlerts.isOn{
            UserDefaults.standard.removeObject(forKey: kAlertsKey)
            UserDefaults.standard.set("On", forKey: kAlertsKey)
            UserDefaults.standard.synchronize()
            print("on")
        }else{
            UserDefaults.standard.removeObject(forKey: kAlertsKey)
            UserDefaults.standard.set("Off", forKey: kAlertsKey)
            UserDefaults.standard.synchronize()
            print("off")
        }

My desire is to share the status Onor Off to 6 different ViewControllers:

  • ViewControllerGUI
  • ViewControllerCreate
  • ViewControllerList
  • ...

My idea was to create an Enum such as:

enum ToggleSwitch: Int{
    case On, Off
    
    var isActive: Bool{
        switch self {
        case .On:
            return true
        case .Off:
            return false
        }
    }
}

But I am not sure on how to follow or what I need to return in my enum case and where do I call it in each ViewController.

Thanks in advance!

CodePudding user response:

I would add a simple extension to UserDefaults:

extension UserDefaults {
    var isAlertsEnabled: Bool {
        get {
            return bool(forKey: "ALERT_KEY")
        }
        set {
            set(newValue, forKey: "ALERT_KEY")
        }
    }
}

Note the use of an actual Bool value instead of working with special string values. Also note that there is no need to remove the old value before setting a new value.

You can use the property anywhere in your project.

For example:

let enabled = UserDefaults.standard.isAlertsEnabled

or:

UserDefaults.standard.isAlertsEnabled = switchAlerts.isOn

FYI - synchronize() is clearly marked as obsolete and shouldn't be used.

  • Related