Reputation: 107
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
Reputation: 6781
I notice 2 things here:
Whenever you programatically adjust the window's root view controller, you need to call window?.makeKeyAndVisible
to show the new screen.
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