Saving and retrieving a bool with UserDefaults

16,802

Solution 1

As Leo mentioned in the comments bool(forKey returns a non-optional Bool. If the key does not exist false is returned.

So it's simply

boolValue = UserDefaults.standard.bool(forKey: "sound")

Calling synchronize() as suggested in other answers is not needed. The framework updates the user defaults database periodically.

Solution 2

Do it like this.

In your first view controller.

  • create an IBoutlet connection to your UISwitch

  • And then the action for your UISwitch. so in the end, your first view controller should look like this.

import UIKit

class FirstViewController: UIViewController {


    @IBOutlet weak var myswitch: UISwitch! // Outlet connection to your UISwitch (just control+ drag  it to your controller)




    override func viewDidLoad() {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

    @IBAction func myswitchAction(_ sender: Any) { // Action for your UISwitch

        var myswitctBool : Bool = false // create a local variable that holds your bool value. assume that in the beginning your switch is offed and the boolean value is `false`

        if myswitch.isOn == true { // when user turn it on then set the value to `true`
            myswitctBool = true
        }
        else { // else set the value to false
            myswitctBool = false
        }


        // finally set the value to user default like this
        UserDefaults.standard.set(myswitctBool, forKey: "mySwitch")
        //UserDefaults.standard.synchronize() - this is not necessary with iOS 8 and later.


    }

}

End of the first view controller

Now in your second view controller

  • you can get the value of userdefault, which you set in first view controller. I put it in the viewdidload method to show you how it works.

import UIKit

class SecondViewController: UIViewController {

        override func viewDidLoad() {
            super.viewDidLoad()


            let myswitchBoolValuefromFirstVc : Bool = UserDefaults.standard.bool(forKey: "mySwitch")// this is how you retrieve the bool value


            // to see the value, just print those with conditions. you can use those for your things.
            if myswitchBoolValuefromFirstVc == true {
                print("true")
            }
            else {
                print("false")
            }


        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()

        }




    }

Hope this will help to you. good luck

Solution 3

Use this line of code:

@IBAction func soundSwitch(_ sender: UISwitch) {
    UserDefaults.standard.set(soundSwitchOutlet.isOn, forKey: "sound")
}

insteadof :

@IBAction func soundSwitch(_ sender: UISwitch) {
    UserDefaults.standard.set(soundSwitchOutlet, forKey: "sound")
}
Share:
16,802
Gabe12
Author by

Gabe12

I'm a 16 year old programmer. I've already created a few apps and I'm currently working on a game. I like technology, science, graphic design, nature, physics, philosophy, and learning basically anything.

Updated on June 23, 2022

Comments

  • Gabe12
    Gabe12 almost 2 years

    I'm trying to save a bool value to UserDefaults from a UISwitch, and retrieve it in another view. However, I've tried following multiple tutorials and stack answers and none seem to work.

    This is how I'm saving it:

    class SettingsViewController: UITableViewController {
    
    @IBOutlet weak var soundSwitchOutlet: UISwitch!
    
    @IBAction func soundSwitch(_ sender: UISwitch) {
    
        UserDefaults.standard.set(soundSwitchOutlet.isOn, forKey: "sound")
    
    }
    

    and this is how I'm trying to retrieve it in another view:

    if let savedValue = UserDefaults.standard.bool(forKey: "sound") {
            boolValue = savedValue
        }
    
    //this is inside viewDidLoad and "boolValue" was declared outside viewDidLoad//
    

    For a reason this code is giving me errors and none of the things I've tried have worked. How can I save a bool to UserDefaults and retrieve it in another view?

    Edit: I think I fixed the first part. However, the way I'm retrieving the boolean seems to be totally wrong. Also: No other stackExchange answer responds to what I'm asking, at least not in swift.

  • Gabe12
    Gabe12 about 7 years
    Thanks! The state of the switch is staying saved, but when I try to use the bool value on another view, it gets stuck on the boolean value it began with.
  • vadian
    vadian about 7 years
    Don't misuse UserDefaults as temporary storage or to pass data between controllers.
  • Eric Aya
    Eric Aya about 7 years
    .synchronize() is useless. Run tests, you'll see by yourself.
  • caldera.sac
    caldera.sac about 7 years
    yep @EricAya we do not need it anymore from iOS 8. accepted and I will remove it. thanx