BLC
BLC

Reputation: 107

Running the specified ViewController

I have a code so that when running, the specified VC is shown if the Switch is turned on.

But nothing happens and switch does not save its value after restarting.

PLS Help

SettingsVC.swift

@IBAction func switchChanged(_ sender: UISwitch) {
    UserDefaults.standard.set(sender.isOn, forKey: "isSwitchOn")
}

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let isSwitchOn = UserDefaults.standard.bool(forKey: "isSwitchOn")
    if isSwitchOn {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let VC2 = storyboard.instantiateViewController(withIdentifier: "ViewController")
        self.window!.rootViewController = VC2;
    }
    // Override point for customization after application launch.
    return true
}

Edit:

override func viewDidLoad() {
    super.viewDidLoad()
    Set.isOn =  UserDefaults.standard.bool(forKey: "isSwitchOn")

    // Do any additional setup after loading the view.
}

Upvotes: 0

Views: 48

Answers (1)

Kelvin Lau
Kelvin Lau

Reputation: 6781

I notice 2 things here:

AppDelegate.swift

Whenever you programatically adjust the window's root view controller, you need to call window?.makeKeyAndVisibleto show the new screen.

UserDefaults

Currently, your code doesn't guarantee that user defaults is saved between restarts. UserDefaults will pick it's own time to save the data on disk, and if you quit your app before that happens, it won't save in time.

I believe that on the simulator, this always happens if you stop running the simulator via Xcode. Since this is fairly important behaviour, you might want to call UserDefaults.standard.synchronize to force a save.

Note that this call is usually done automatically for you in specific intervals; You're doing it explicitly because you can't afford to miss out on it.

Upvotes: 1

Related Questions