Delete UserDefaults data in every 24 hours

I’m using UserDefaults with SwiftUI to save my data from multiple variables and I use those values for graphs. My goal would be to only show the user daily progress, so I would need to delete the stored data from UserDefaults or reset the variable values back to 0 in every day.
I assume Apple Fitness app does something similar with the ‘Activity rings’ which resets every day, but I don’t know how to achieve something like this. Every help would be appreciated.

My code:

@Published var waterGraph: Float = UserDefaults.standard.float(forKey: "waterGraph") {
        didSet {
            UserDefaults.standard.set(self.waterGraph, forKey: "waterGraph")
        }
    }

Hi @kewika,
You can store the data with the date as a key, so every day the data will be nil and you can add data to that date. You might want to wrap the waterGraph along with some other metrics and save them all as an object under the date key.

cheers,

This topic was automatically closed after 166 days. New replies are no longer allowed.