Enable state restoration on iOS

237 views Asked by At

I'm trying to enable state restoration for my app but I can't work it out. I've set unique restoration identifiers to all view controllers in the storyboard. I've overridden these methods on the app delegate:

func application(_ application: UIApplication, shouldSaveSecureApplicationState coder: NSCoder) -> Bool {
    return true;
}

func application(_ application: UIApplication, shouldRestoreSecureApplicationState coder: NSCoder) -> Bool {
    return true;
}

I don't know what else I'm supposed to do. I tried putting breakpoints inside encodeRestorableState and decodeRestorableState but they don't seem to be called while the debugger is attached. I'm using storyboards so it's my understanding that everything else should happen automatically.

To test state restoration, I run the app in the simulator, change the state (select a tab in the tab bar), press the home button in the simulator, quit the app from Xcode, and finally launch the app again from the simulator by clicking the icon on the home screen. For a brief moment, I can see the tab I selected previously but then it switches to the first tab.

From what I can tell, this should be all I need to do. I've tried a few variations of procedures for triggering state restoration like closing the app in the iOS task switcher but they all have the same results. I've read in some places that I need to create the view controller instances but I shouldn't need to do that if I'm using a storyboard.

I thought maybe the currently selected item in a tab bar is something that isn't saved and restored automatically so I tried putting this in the tab bar view controller:

override func encodeRestorableState(with coder: NSCoder) {
    coder.encode(selectedIndex, forKey: "selectedIndex");
    super.encodeRestorableState(with: coder);
}

override func decodeRestorableState(with coder: NSCoder) {
    super.decodeRestorableState(with: coder);
    selectedIndex = coder.decodeInteger(forKey: "selectedIndex");
}

That had no effect. I can't figure out what I'm doing wrong.

0

There are 0 answers