0

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.

Byte
  • 629
  • 2
  • 11
  • 29
  • I recommend writing an `NSURL` to `NSUserDefaults` that matches the any navigation controller path detailing how to get to the current state. – Abhi Beckert Jul 26 '16 at 06:04
  • @AbhiBeckert can you please describe in detail in answer ? – Byte Jul 26 '16 at 06:06
  • I haven't got time to write a full answer, perhaps you can do that? But for example in a music app the URL might be `https://my-music-app.com/playlists/playlist-name/song-name` to show the "now playing" controller for a specific song, with the back button taking you to a playlist containing that song, and another back button taking you to the list of playlists. This URL can be used for other things, like a share button within the app. And you might also have an actual web server that can handle the URL as well, for users who don't have the app installed. – Abhi Beckert Jul 26 '16 at 06:07
  • I am sorry I am not able to understand this. Can someone please write a detailed answer. – Byte Jul 26 '16 at 06:16

1 Answers1

0

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.

lubilis
  • 3,942
  • 4
  • 31
  • 54