Marcelo_M
Marcelo_M

Reputation: 23

How to make a Switch keep its state after switching viewControllers in swift 4?

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.

Upvotes: 0

Views: 170

Answers (1)

Willjay
Willjay

Reputation: 6469

Your logic is right. However, viewDidLoad will be called only once when the view controller is loaded. If you go background and open again, viewDidLoad will not be called again.

There are some function in UIApplicationDelegate you can use, like applicationWillEnterForeground, applicationWillTerminate, applicationDidBecomeActive, applicationWillResignActive, applicationDidEnterBackground... choose one that fits your scenario.

Or you can just add observer listening to UIApplicationWillEnterForeground in your viewcontroller, and update your switch whenever it is called.

Upvotes: 1

Related Questions