in my app I have a couple lines of code preparing a local notification for 7 am. The problem is that every time I close the app the notification will be showed. I only want this to happen ones after the set time is passed.
In my applicationDidEnterBackground:
NSCalendar *calendar = [NSCalendar currentCalendar]; // gets default calendar
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, day,hour and minutesfor today's date
[components setHour:7];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notifyAlarm = [[UILocalNotification alloc] init];
if (notifyAlarm) {
notifyAlarm.fireDate = [calendar dateFromComponents:components];
notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
notifyAlarm.repeatInterval = 0;
notifyAlarm.soundName = @"not.wav";
notifyAlarm.alertBody = @"test";
[app scheduleLocalNotification:notifyAlarm];
}
In my applicationWillEnterForeground:
UIApplication *app = [UIApplication sharedApplication];
NSArray *oldNotifications = [app scheduledLocalNotifications];
if ([oldNotifications count] > 0) {
[app cancelAllLocalNotifications];
}
I think the problem is in the [oldNotifications count]. After implementing a NSLog to check it's amount it shows every time 0. This should count up, right? Any help??? :)
try this code. if you want to repeat NSLocalNotification daily then you need to set repeatInterval to NSDayCalender unit.
NSCalendar *calendar = [NSCalendar currentCalendar]; // gets default calendar
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, day,hour and minutesfor today's date
[components setHour:7];
UIApplication *app = [UIApplication sharedApplication];
UILocalNotification *notifyAlarm = [[UILocalNotification alloc] init];
if (notifyAlarm)
{
notifyAlarm.fireDate = [calendar dateFromComponents:components];
notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
notifyAlarm.repeatInterval = NSDayCalendarUnit;
notifyAlarm.soundName = @"not.wav";
notifyAlarm.alertBody = @"test";
[app scheduleLocalNotification:notifyAlarm];
}