A complete guide to App State Restoration in iOS

Overview

App State restoration is for the user to come back to the app as they left it last time before it is a suspended app. Returning an app to its previous app state offers a better user experience and saves time for the user.

Tool Used: Xcode 9.2, Swift 4+

To implement app state restoration you just have to follow below steps.

Step 1: Enable app state restoration

Add this function in AppDelegate.swift file

true value return in the application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) function that informs the system to store the current app state of your views and view controllers when the app goes to background and true value return in the application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) function that informs the system to perform to restore state when the app restart.

Step 2: Set restoration Identifiers

Restoration identifiers is a unique string name of any view controller or view that restoration will identify and restore. The restorationIdentifier property can be set either in Storyboard file, Nib file or code.

Using storyboard:
– Use same name of storyboard ID.

Using code:
– Add this code in viewDidLoad function.

Step 3: UIStateRestoring Protocol

Function encodeRestorableState(_:) call when the app goes to the background for app state is saved and function decodeRestorableState(_:) call when the app to restored in any view controller with a restorationIdentifier.

Please see this code in our demo for more clear.

Step 4: UIViewControllerRestoration Protocol

Restoration view controller class must conform UIViewControllerRestoration protocol and the method of UIViewControllerRestoration protocol should be used to return same view controller instance if it exist else return nil.

We have implemented this kind of in our demo.

NOTE:

Source: This part of Apple’s docs

The system automatically deletes an app’s preserved state when the user force quits the app. Deleting the preserved state information when the app is killed is a safety precaution. (As a safety precaution, the system also deletes preserved state if the app crashes twice during launch.) If you want to test your app’s ability to restore its state, you should not use the multitasking bar to kill the app during debugging. Instead, use Xcode to kill the app or kill the app programmatically by installing a temporary command or gesture to call exit on demand.

More Reference:

Preserving and Restoring State in Apple’s docs

mm

Sandeep Joshi iOS Team Lead

I’m Sandeep Joshi - an iOS developer at Yudiz Solutions Pvt. Ltd. - a leading iPhone App Development company. I am ambitious and intensely interested in what I do. You'll quickly find that I do not merely develop software - I develop highly maintainable, elegant code that will save you enormous sums in the long run.

Comments are closed.

Top