-1

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()
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
undervine
  • 59
  • 6
  • 1
    Can you post some related code also – Umair Aamir Jan 17 '18 at 14:27
  • 2
    It is difficult to offer solutions when the problem statement is simply, ["it doesn't work"](http://idownvotedbecau.se/itsnotworking/). Please [edit] your question to give a more complete description of what you expected to happen and how that differs from the actual results. See [ask] for hints on what makes a good explanation. – Toby Speight Jan 17 '18 at 14:33
  • you need to use encoder and decoder for UserDefaults because you are dealing with custom class object – Vinodh Jan 17 '18 at 15:18
  • I made VendingMachine class adopt Codable protocol. – undervine Jan 18 '18 at 01:24

1 Answers1

1

Encode/Decode your object before. You can use for instance this code below :

extension UserDefaults {
    func persist<Value>(_ value: Value, forKey key: String) where Value : Codable {
        guard let data = try? PropertyListEncoder().encode(value) else { return }
        set(data, forKey: key)
    }

    func retrieveValue<Value>(forKey key: String) -> Value? where Value : Codable {
        return data(forKey: key).flatMap { try? PropertyListDecoder().decode(Value.self, from: $0) }
    }
}
GaétanZ
  • 4,870
  • 1
  • 23
  • 30