Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving and retrieving a bool with UserDefaults

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.

like image 329
Gabe12 Avatar asked Feb 27 '17 05:02

Gabe12


People also ask

What is the use of userdefaults in Java?

It’s easy to use and pretty much supports all kinds of value types like Dictionary, Array, Any, String, Int, Float, Double, Bool, URL. The UserDefaults class is thread-safe. You can check here how to use UserDefaults with Propertywrapper.

What are the different types of values supported by userdefaults?

It’s easy to use and pretty much supports all kinds of value types like Dictionary, Array, Any, String, Int, Float, Double, Bool, URL. The UserDefaults class is thread-safe.

How to add usersettings to observable object?

Inside the new file, implement a class called UserSettings, conforming to the ObservableObject, with one @Published String variable holding username from the UI form. Remember to import Combine framework.

How do I preserve a user’s username in a project?

Build and run your project. Type in a username into the text field, force quit the app and re-open it – the username should be preserved. The result should look like this:


3 Answers

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.

like image 151
vadian Avatar answered Nov 15 '22 06:11

vadian


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

like image 40
Chanaka Anuradh Caldera Avatar answered Nov 15 '22 08:11

Chanaka Anuradh Caldera


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")
}
like image 34
Brijesh Shiroya Avatar answered Nov 15 '22 07:11

Brijesh Shiroya