Home > Software engineering >  Save UISwitch's toggled data in UserDefaults
Save UISwitch's toggled data in UserDefaults

Time:10-29

I've declared a boolean with default value true, if my UISwitch is on I want boolean variable to be true else false, my code works fine until I try to store that boolean in UserDefaults when I reset the xCode Simulator I check with print method but it is not really saved... any solution will be appericated.

    var userDefaultSamarxvo:Bool = true
    let defaults = UserDefaults.standard
    override func viewDidLoad() {
        super.viewDidLoad()
        defaults.set(userDefaultSamarxvo,forKey: "Samarxvo")   // set of userdefault
        if userDefaultSamarxvo {
            print("hello")
        }else{
            print("olleh")
        }
    }
    @IBAction func samarxvoDidChange(_ sender: UISwitch) {
        if sender.isOn {
            userDefaultSamarxvo.toggle()
            print("samarxo")
        }else{
            userDefaultSamarxvo.toggle()
            print("samarxo 1 ")
        }
    }

CodePudding user response:

In viewDidLoad you want to load the saved value from user defaults. When the switch changes you need to save the new value to user defaults.

Setting a local variable (userDefaultSamarxvo) doesn't change what is stored in the user defaults; Local variables don't bind to user defaults storage.

There is an added complication; bool(forKey) will return false if there is no value for the key in UserDefaults. If you want the initial value to be true then you need to handle that in some way. You can use object(forKey) which returns an optional

var userDefaultSamarxvo:Bool = true {
   didSet {
       UserDefaults.standard.set(userDefaultSamarxvo, forKey:switchKey)
   }
}
let defaults = UserDefaults.standard
let switchKey = "Samarxvo"

@IBOutlet weak var theSwitch: UISwitch!

override func viewDidLoad() {
    super.viewDidLoad()
    if defaults.object(forKey: switchKey) != nil {
        userDefaultSamarxvo = defaults.bool(forKey: switchKey)
    }

    self.theSwitch.isOn = userDefaultSamarxvo
}

    
@IBAction func samarxvoDidChange(_ sender: UISwitch) {
    userDefaultSamarxvo = sender.isOn        
}

I have used a didSet clause to update the user defaults value when the property changes.

  • Related