Swift Save viewcontroller state using coder beyond app close

后端 未结 1 1919
不知归路
不知归路 2021-01-22 10:25

I am using Xcode 8 and swift 2.3

I want to save the entire view controller to file and restore state even after app closes. I searched everywhere and found we need to us

相关标签:
1条回答
  • 2021-01-22 11:09

    TL;DR:
    There are key steps and methods required to implement state restoration in your app.

    1. Opting-in for App State Restoration in App Delegate by returning true for these methods shouldSaveApplicationState and shouldRestoreApplicationState.
    2. Setting Restoration Identifier for view controllers that you want state restoration implemented in.
    3. Implementing encodeRestorableStateWithCoder and decodeRestorableStateWithCoder methods in your view controller. The former is used to save any state information of your view controller to disk using encodeObjectForKey method. The latter shall be used to restore the state back from your saved contents to the disk by using decodeObjectForKey method.

    Watch this awesome blog post about State Restoration for easier grasp. If you have time, also do spend on watching State Restoration WWDC Session.


    There is no need to save your entire ViewController yourself. UIKit does that for you when you set your Restoration Identifier (In Interface Builder). The only thing we need to focus for state restoration is to save your essential properties needed to re-create your app's "State", for example, a Bool property which determines whether you want to display a specific button or not.

    Now coming to your series of questions....

    Can I just save self.view and can it save all subviews automatically ?

    You do not need to save any of your views. All subviews will be handled by UIKit. Encode your required properties (such as Bool flags, count variables, key properties that can be used to fetch data from api call for your datasource etc.) inside encodeRestorableStateWithCoder method. Don't forget to re-contruct your view controller's state from decodeRestorableStateWithCoder. Both of these methods belond to UIStateRestoring protocol.

    I need to init without coder at start by just using

    No need to do any fancy inits.

    How do I save all this coded data to file using NSKeyedUnarchiver and retrieve back?

    As I said earlier, implement necessary UIStateRestoring protocol methods to save and restore your app's state.

    0 讨论(0)
提交回复
热议问题