简体   繁体   中英

Delete saved data form UserDefaults at a specific time?

I'm using UserDefaults with SwiftUI to save my data from multiple variables and I use them for graphs which shows some daily information. Is there a way to delete or reset the saved data form UserDefaults to only contain the data form the current day? For example delete the data at 23:59 every night.

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

Do you really need to delete the data from your UserDefaults at exactly 23:59? If you do then you would have to run background tasks which can be quite complicated. Another easier alternative is to clear the UserDefaults each time the user opens the app and if it has been 24 hours since your UserDefaults data was stored. Store a value in your UserDefaults called "in24hours" and set its value to 24 hours from the current time. In the appDelegate's didFinishLaunchingWithOptions function, check for the date stored in the userDefaults "in24hours" and if the current time is greater than the time in that variable, then you can clear your userDefaults there. You can set the "in24hours" variable whenever you want (after you add your to be deleted data in UserDefaults). Instead of setting the "in24Hours" to 24 hours from the current time and date, you could also set it to midnight on the following date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM