I'm a first time developer and just launched an app. I'm trying to add a feature to my app where when they go to settings, and disable audio, I wan't that data to be stored and for the audio to be disabled every time. Any idea on how to do this?
1 Answers
Just have a variable that's a boolean that is based on the switch. Then use UserDefaults to store the data.
var audioDisabled = true
UserDefaults.standard.set(audioDisabled, forKey: "audioDisabled")
The variable in the code above is based on whether the user has the audio on or off. I then set it to storage through UserDefaults, which will hold values even after the app is closed. The key will be how you will have access to the stored value.
If you want to retrieve that data when the user opens the app, use
audioDisabled = UserDefaults.standard.object(forKey: "audioDisabled") as? Bool ?? true
You can also do false after the ?? if the default option is no audio. I just set the default to true if the user went to the setting and configured the audio setting
In here, I'm using the value using the key that I set above. I'm telling the program that if the stored value exist, it will be in the form of a Bool and if not, then audioDisabled
will be set to true
I hope that helps

- 16
- 5
-
1That helps a lot but how do I set the variable based on the switch? – Dhruv S. May 19 '20 at 21:22
-
Connect the switch to your code like as if it is a button (set the connection to action and the type to UISwitch). Then, underneath the switch method (when the switch gets toggled) do an if statement to see if the switch is on (if sender.isOn { *sets audioDisabled to false* } else { *sets audioDisabled to true* } // then do the UserDefault after you set the variable in the if statement) – J26 May 19 '20 at 21:32