Saving and retrieving a bool with UserDefaults

2020-03-25 08:24发布

问题:

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.

回答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.



回答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



回答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")
}


回答4:

Try this:

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

  //this is inside viewDidLoad and "boolValue" was declared outside viewDidLoad//

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