So I have this mini school project where in the beginning I have an off switch, the idea is to turn it on and be able to move to other viewControllers but when i get back the switch is still on, the thing is that when opening the app after closing it, it must be turned off. Ive seen other similar questions but none ask on how to maintain the off state after closing the app.
override func viewDidLoad() {
super.viewDidLoad()
switchOutlet.isOn = UserDefaults.standard.bool(forKey: "isOnSwitch")
{
@IBAction func switchAction(_ sender: Any) {
let isOnSwitch = UserDefaults.standard.bool(forKey: "isOnSwitch")
if isOnSwitch == true {
UserDefaults.standard.set(false, forKey: "isOnSwitch")
} else { UserDefaults.standard.set(true, forKey: "isOnSwitch")}
This code only works to make sure the switch is On at all times, even when entering the app for the first time.