I archived an object which adopted Codable, and implemented storing the object data when the app enters background, loading them when the app is reopened.
But it doesn't work.
How can I check the UserDefaults' changes after terminate and reopen the simulator?
I made 'Machine' class Codable, and implemented 'MachineStore' class which archives a Machine object.
Saving data:
func saveChanges() {
var data = Data()
do {
data = try encoder.encode(self.machine)
} catch {
NSLog(error.localizedDescription)
}
UserDefaults.standard.set(data, forKey: MachineStore.Key)
}
Loading data:
func loadMachine() {
guard let data = UserDefaults.standard.data(forKey: MachineStore.Key) else { return }
do {
machine = try decoder.decode(VendingMachine.self, from: data)
} catch {
NSLog(error.localizedDescription)
}
}
And I used MachineStore in AppDelegate.
let machineStore: MachineStore = MachineStore()
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
machineStore.loadMachine()
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
machineStore.saveChanges()
}