I'm trying to set a value to 0 every 24 hours regardless of whether the user has opened the app or not. I know my app can't run a timer in the background, so how can I have the value automatically reset every 24 hours?
I've tried saving the last time my user ran the app and checking if it's within 24 hours of the current time, but that won't reset the value if it is within 24 hours. (Also, when I save a variable in UserDefaults to Date() and print it, it gives me a time 16 hours in the future for some reason.) Even if I use NSDate, I think I'd still have this problem.
Thank you for reading and I'd really appreciate any ideas :)
Do you really need to have your apps values reset in exactly 24 hours? Do you just want to check if it has been past the 24 hour period since last reseting your values and reset it if it has been past 24 hours each time your app launches? If you don't need to reset it at a specific time, then you can add the following code to your app delegate
if UserDefaults.standard.bool(forKey: "didLaunchBefore") == false{
//only runs the first time your app is launched
UserDefaults.standard.set(true, forKey: "didLaunchBefore")
//sets the initial value for tomorrow
let now = Calendar.current.dateComponents(in: .current, from: Date())
let tomorrow = DateComponents(year: now.year, month: now.month, day: now.day! + 1, hour: now.hour, minute: now.minute, second: now.second)
let date = Calendar.current.date(from: tomorrow)
UserDefaults.standard.set(date, forKey: "tomorrow")
}
if UserDefaults.standard.object(forKey: "tomorrow") != nil{//makes sure tomorrow is not nil
if Date() > UserDefaults.standard.object(forKey: "tomorrow") as! Date {// if todays date is after(greater than) the 24 hour period you set last time you reset your values this will run
// reseting "tomorrow" to the actual tomorrow
let now = Calendar.current.dateComponents(in: .current, from: Date())
let tomorrow = DateComponents(year: now.year, month: now.month, day: now.day! + 1, hour: now.hour, minute: now.minute, second: now.second)
let date = Calendar.current.date(from: tomorrow)
UserDefaults.standard.set(date, forKey: "tomorrow")
//reset your values here
}
}