Faisal Syed
Faisal Syed

Reputation: 931

Detecting Day Change in iOS App

So I've been doing a bit of research on how to tell if it's a new day in my iOS app. Basically, I want to reset a bunch of values to 0 as soon as a new day starts. I've seen that I can use "UIApplicationSignificantTimeChangeNotification" which sends a notification at midnight. However, will this still fire if the user killed the app at 9:00AM and opens it up again at 9:00AM the next day?

I also saw that I could use "NSCalendarDayChangedNotification" which to my understanding has the same behavior. My only concern is that if either of these will accomplish detecting a day change even after the user kills the app.

Ideally I'd like to put add the notification observer at the top of my .m file in the viewDidLoad like so:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resetValues) name:UIApplicationSignificantTimeChangeNotification object:nil];

and then somewhere else in the file...

- (void)resetValues {

... // reset values to 0

}

The goal would be for this notification to trigger at the beginning of every day change. Would the code above achieve the behavior I'm looking for?

Upvotes: 4

Views: 2175

Answers (2)

Ofir Malachi
Ofir Malachi

Reputation: 1286

System observer:

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadData) name:NSCalendarDayChangedNotification object:nil];

https://developer.apple.com/documentation/foundation/nscalendardaychangednotification?language=objc

Upvotes: 0

vadian
vadian

Reputation: 285082

Solution which saves an integer value (the day) in NSUserDefaults

  • In AppDelegate create a method checkDayChange which compares the day component of the current date with a saved value in NSUserDefaults (default is 0). If the values are not equal, call resetValues and save the current day.

    - (void)checkDayChange
    {
       NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
       NSInteger currentDay = [[NSCalendar currentCalendar] component:NSCalendarUnitDay fromDate:[NSDate date]];
       NSInteger savedDay = [defaults integerForKey:@"day"]; // default is 0
       if (currentDay != savedDay) {
           [self resetValues];
           [defaults setInteger:currentDay forKey:@"day"];
       }
    }
    
  • Observe NSCalendarDayChangedNotification with selector checkDayChange

  • Call checkDayChange also in applicationDidFinishLaunching and applicationDidBecomeActive

Upvotes: 7

Related Questions