irkinosor
irkinosor

Reputation: 776

How do I reset a variable at the start of each day?

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

Answers (1)

fiks
fiks

Reputation: 1045

You can store in the user defaults this value.

So the flow is the following:

  1. When the app is launched or became active you check whether the value of the variable in the user defaults is the same as the current day (e.g. 25/07/2016), then do nothing.
  2. If the value is different, then you update the value in the user defaults with the current day.

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

Related Questions