My app has a view controller that has to be restored even if the user kills the app himself, and shouldRestoreApplicationState
doesn't do that; if the user killed the app I get back to the first controller.
So is there a way to do what I want, get the state to be restored every single time?
If that's impossible with state restoration, I thought maybe I could save the view controller to my persistent store and present it from my appDelegate, but I couldn't figure that out yet. I'd have to rebuild the whole navigation stack, including a tab bar controller and multiple navigation controllers up to that view, from the appDelegate. Is that a good idea? How should I go about that?
I tried variations of this:
let bookInfoStoryboard = UIStoryboard(name: "BookInfo", bundle: nil)
let controller = bookInfoStoryboard
.instantiateViewControllerWithIdentifier("bookInfoTableViewController")
self.window?.makeKeyAndVisible()
self.window?.rootViewController!.presentViewController(controller, animated: true, completion: nil)
But I keep getting various errors.
Ideally I wanted to restore the state of every view controller, but it must happen every time. Is there a better way to do that?
Thanks,
Daniel
Persisting view controllers is not possible, as they carry a lot of transient information and very little persistent one.
What you can do is to save the configuration that represents the hierarchy of view controllers to user defaults
, and rebuild from there. For example assuming you have a tab view with file system like navigation, you can persist to user defaults
a string like this: bookmarks.folder1.subfolder2.file18.playing.position=19.28
. This might correspond to a video file being played and reaching 19.28 seconds before the application crashed, or was terminated by OS.
By using schemas like the one above you can restore the controllers to a state very close to the one before the last session ended. And the best part is that the user doesn't even have to know that your application started all over, he'll get the same experience as the last time he navigated through the application.
Ofcourse the restoral depends on the complexity level of the application, and might not be applicable for all flows within the application, however for such cases you can at least bring the user back to an application state closer to the one before exit.