Reputation: 776
I have a variable that keeps track of user statistic I want to reset at the beginning of each day. How can I do that? Since the application is not allowed to run in the background, it seems I will have to do the check every time the application is active but I don't know how to reset the variable I have only once. This is the function I wanted to use:
let beginingOfDay = NSCalendar.currentCalendar().startOfDayForDate(NSDate())
func resetCurrentTime(){
// Date comparision to compare current date and begining of the day.
let dateComparisionResult:NSComparisonResult = NSDate().compare(beginingOfDay)
if dateComparisionResult == NSComparisonResult.OrderedDescending || dateComparisionResult == NSComparisonResult.OrderedSame {
// Current date is greater or equal to end date.
currentTime = 0 //reset the time tracker
}
}
I wanted to use this function to check when the application is launched but the problem is that the application could be launched many time a day. How I can reset my variable only once at the beginning of a day if the user is using the application or when the application becomes active or is launched for the first time that day? Thanks
Upvotes: 2
Views: 2424
Reputation: 1045
You can store in the user defaults this value.
So the flow is the following:
If the app is running and the date is changed, you can update the value of your variable by subscribing to this notification:
UIApplicationSignificantTimeChangeNotification
Upvotes: 6