Enabling State Preservation and Restoration in Your App

 

  • What is Preservation and Restoration State?

    • Preservation & Restoration State is a feature provided by Apple to store application’s last state.
    • When the user keeps the application in the background, killed or suspended and launched again, it will redirect to last opened page(view controller).
    • State Preservation & Restoration process is useful when the user is working on something and for some reason, he/she might press Home button to minimize the app to use another app.
    • After 3 mins, if your application is not opened by the user, your app will be suspended in background and user will lose all his/her work.
    • When the user clicks again on the app, It will launch from the first page.
    • To overcome of this scenario, If we enable Preservation and Restoration state in our app, User will never lose his/her work.
    • Also, your app will not consume more battery to run the app in the background as it will not be running in the background.
  • How can we enable Preservation & Restoration State in our App? 

To enable Preservation & Restoration in our app, we need to set ‘restorationIdentifier’ by programmatically or ‘Restoration ID in storyboard view controller.

We can even select ‘Use StoryBoard ID for Restoration ID.

One most important thing is that, If we want to implement State Reservation & Restoration in our app, we need to set each and every view controller’s ‘restoration Identifier’. If we miss single view controller, Restoration will not work in the app.

 

  • Tutorial:

    1. Enable Restoration in AppDelegate.swift
    2.  // MARK: - Enabled Restoration
       // This function will save your application state when app enters in background.
       func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
               return true
       }    
      // This will allow to restore app and shows previously opened page
       func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
               return true
       }
      
    3. Set Restoration Identifiers
      • Restoration Identifiers is simply a unique string name of the view or view controller that Restoration will identify and restore. We can use even StoryBoard ID as Restoration Identifier.
      • Restoration can be set either in a StoryBoard file or in code.
      • If you do not want to set Restoration ID in StoryBoard file, then in code just add one line code in ViewDidLoad() function… .
      • self.restorationIdentifier = "RestoredView1"
    4. UIStateRestoring Protocol
      • To implement State Restoration, UIKit does a lot for us, but there are some points that we need to do from our side.
        1. Need to tell UIKit that your app wants to take participate in State Restoration, which we have done in AppDelegate.swift file by adding two functions.
        2. Need to set a unique or same as StoryBoard ID for Restoration ID in all ViewController as per shown on above screenshot.
        3. Need to do Encoding and Decoding data to reconstruct View Controller to its previous state. This I will show you below.
      • Every ViewController with a Restoration ID will receive a call to encodeRestorableState(with coder: NSCoder) of the UIStateRestoring protocol when the app is saved. Additionally, the ViewController will receive a call to decodeRestorableState(with coder: NSCoder) when the app is restored.

Demo:

  1. Create one Project, add another View Controller in it.
  2. Set Restoration ID & StoryBoard ID to both View Controllers.
  3. Add shouldSaveApplicationState:(_:) and shouldRestoreApplicationState:(_:) methods in AppDelegate.swift file by returning ‘true’ value.
  4. Now, go to SecondViewController.swift file that you have added in your project.
  5. Add one textField and set its IBOutlets.
  6. Add one Button in your default ViewController.swift file which will redirect you on SecondViewController.swift file.
  7. Add below lines of code in SecondViewController.swift file:
  8.     override func encodeRestorableState(with coder: NSCoder) {
           if let str = textFieldData.text{
               coder.encode(str, forKey: "TextData")
           }
           super.encodeRestorableState(with: coder)
        }
    
       override func decodeRestorableState(with coder: NSCoder) {
           textFieldData.text = coder.decodeObject(forKey: "TextData") as? String
           super.decodeRestorableState(with: coder)
       }
    
       override func applicationFinishedRestoringState() {
           guard let str = textFieldData.text else {
               return
           }
           print("Restored value textFieldData.text: \(str)")
       }

     

  9. Now Run app, App will show Button in the center of the screen. Click on that, It will redirect to the second page. Now write anything in the textField. Press ‘CMD+SHIFT+H’. Now click on Stop project button.
  10. As per normal process, If we run the project again, the app will show a Button in the center of the screen. But we have added restoration code in SecondViewController.swift.
  11. Run the project again, App will directly show textField with prefilled with text that we have written before app killed. The app will be restored from an earlier state.

Have something to share on the same? Tweet us on Twitter @letsnurture or drop a post on the official FaceBook page of LetsNurture. Share your thoughts with us, we will be happy to have a discussion on the same.

Want to work with us? We're hiring!