Reset UILocationNotification fire date set for everyday

79 views Asked by At

I've a function in my app which allowed to use for max. 3 times/day to a user – once he/she used it for all 3 times, they can't not use it again until next day. I'm using UILocationNotification in my app, to show a notification each day. If a user open my app, and he didn't use those functions for that particular day then, I'll set up notification to fire at exactly 4.00pm for that day. But now what I want is, while user is using the app – if he/she used that function for 3 times then the notification should not get fire and it should set for the next day at the same time.

This is how I'm showing up local notification.

- (void) fireNoteForEachDay {
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    UILocalNotification *notif = [[UILocalNotification alloc] init];
    NSCalendar *gregCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComponents = [gregCalendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]];
    [dateComponents setHour:16];
    [dateComponents setMinute:0];
    [dateComponents setSecond:0];
    [notif setFireDate:[gregCalendar dateFromComponents:dateComponents]];
    [notif setAlertBody:@"Come back to the app – to use '<function name>' !"];
    [notif setRepeatInterval:NSDayCalendarUnit];
    [notif setTimeZone:[NSTimeZone defaultTimeZone]];
    [[UIApplication sharedApplication] scheduleLocalNotification:notif];
}

If I use all three functions at 3.00pm today – so now it should reset for tomorrow's date at 4.00pm.

How do I do that?

1

There are 1 answers

0
Hemang On BEST ANSWER

Get tomorrow

NSDateComponents *tomorrowComponents = [NSDateComponents new];
tomorrowComponents.day = 1 ;
NSCalendar *gregCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *tomorrow = [gregCalendar dateByAddingComponents:tomorrowComponents toDate:[NSDate date] options:0];

Add time for tomorrow

NSDateComponents *tomorrowAtTimeComponent = [gregCalendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:tomorrow];
tomorrowAtTimeComponent.hour = 16;
tomorrowAtTimeComponent.minute = 0;
NSDate *tomorrowAt4pm = [gregCalendar dateFromComponents:tomorrowAtTimeComponent];

Reset note

[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *notif = [[UILocalNotification alloc] init];
[notif setFireDate:tomorrowAt4pm];
[notif setAlertBody:@"Come back to the app – to use '<function name>' !"];
[notif setRepeatInterval:NSDayCalendarUnit];
[notif setTimeZone:[NSTimeZone defaultTimeZone]];
[[UIApplication sharedApplication] scheduleLocalNotification:notif];