Byte
Byte

Reputation: 629

Saving state of application in ios using Swift

I have four viewControllers in my application. Now lets suppose user is currently on the second viewController and He terminates the application.

Now how can I save this state, so that when user reopen the application he should be presented with the second viewContoller, and should be able to navigate back to first viewContoller as well.

The solution I have in my mind is to simply save a variable of current screen in userDefaults and then make that viewController a rootViewController. But I know its not the proper solution and I will lose navigation as well. Please guide me thanks.

Upvotes: 0

Views: 1669

Answers (1)

lubilis
lubilis

Reputation: 4170

If you haven't yet, create a class called BaseViewController that should be extended from all your UIViewControllers:

class BaseViewController: UIViewController {

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        // always remember last controller shown
        NSUserDefaults.standardUserDefaults.setObject(classForCoder(), forKey: "lastController")
    }
}

You can save controller class name, an int identifier or somenthing you want. Then, in app delegate on application start you can read this value and make your custom logic to open the right controller.

if NSUserDefaults.standardUserDefaults().stringForKey("lastController") == MyCustomViewController.classForCoder() {
    // open MyCustomViewController
}

Then when user goes back, redirect to the right UIViewController according your application flow.

Upvotes: 0

Related Questions