swiftencodingdecodingstate-restoration

How to rewrite this encoding for a UISwitch and also how to decode it?


I'm trying to save the state of some switches and restore it when the app launches again but when I wrote this :

override func encodeRestorableState(with coder: NSCoder) {
    super.encodeRestorableState(with: coder)
    coder.encode(Int32(self.runSwitch1.state.rawValue), forKey: CodingKey.Protocol)
}

I got this error :

Cannot convert value of type 'CodingKey.Protocol.Type' to expected argument type 'String'

What should I do ?


Solution

  • If you mean't was restoring state between app switches provide a unique key against the type to be encoded

    override func encodeRestorableStateWithCoder(coder: NSCoder) {
        coder.encode(self.runSwitch1.isOn, forKey: "switchState")    
      super.encodeRestorableStateWithCoder(coder)
    }
    

    //Decode later when state restore

    override func decodeRestorableStateWithCoder(coder: NSCoder) {          
      super.decodeRestorableStateWithCoder(coder)
    }
    

    And restore switch state by

    override func applicationFinishedRestoringState() {
       let restoredState =coder.decodeBool(forKey: "switchState") 
       self.switch.setOn(restoredState, animated: false)
    }
    

    Use CoreData or other db based framework to sustain states even after app is closed. Or you can do it using userdefaults

    class MySavedSwitchStates:NSObject {
        var userDefault = UserDefaults.standard
        private override init() {
        }
        static let shared = MySavedSwitchStates()
    
        //This saves state to preferences
        func setSwitchState(_ state:Bool) {
            userDefault.set(state, forKey: "SOME_SWITCH_STATE")
        }
    
        //This retrieve the current state of switch
        func retrieveSwitchState() -> Bool {    
            return userDefault.bool(forKey: "SOME_SWITCH_STATE")
        }
    }
    

    and in your controller

    //In your controller viewdidLoad
    let restoredState = MySavedSwitchStates.shared.retrieveSwitchState()
    self.switch.setOn(restoredState, animated: false)