2

I am trying to determine if user selected the "reset" button after the app restarts. With this code, it will go back to the root controller when the app is open or in the background. Once I terminate the app and re-open, the app is still as if the button was never pressed.

@IBAction func resetClicked(_ sender: Any) {
            UserDefaults.standard.set("delete was pressed", forKey: "deleteClicked")
            print(UserDefaults.standard.string(forKey: "deleteClicked"))
            let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: infoNavController.ID) as! infoNavController
            (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.changeRootViewController(vc)
}

I try to call this UserDefault in App Delegate:

func applicationDidBecomeActive(_ application: UIApplication) {
        let defaults = UserDefaults.standard
        if let check = defaults.string(forKey: "deleteClicked") {
            let  vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: infoNavController.ID) as! inftoNavController
            (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.changeRootViewController(vc)
            print("Delete was pressed, root controller is now infonavController \(check)")
        }
        
        print("applicationDidBecomeActive")
    }

But no avail here. I also wrote this code in didfinishlaunchingwithoptions but it also does not read there. Does anyone have any suggestions for this?

rmr84
  • 33
  • 4
  • It works for me. I copied you code and after I restarted the app it printed: `Delete was pressed, root controller is now infonavController delete was pressed `. So your code is good. Probably you can't access the UserDefaults? But I've never faced this kind of issue.. – FrugalResolution Sep 27 '22 at 15:16
  • @Felix you were right, the solution was actually because I needed to access User Defaults in Scene Delegate and reset the root controller there. Thanks! – rmr84 Sep 27 '22 at 17:05

1 Answers1

1

I did figure this out. Needed to defaults.synchronize() in the appropriate places, such as Scene Delegate and ``didFinishLaunchingWithOptions``` in App Delegate

rmr84
  • 33
  • 4
  • If you needed to use the "synchronize" method to get your code works, then the problem was not solved, it was just hacked. Foundation documentation states that synchronize method is deprecated. – Blazej SLEBODA Nov 11 '22 at 22:54