Solved this , the problem was the notification was being programmed in the past ( as in before [NSDate date ] - the current date ) , and i was trying to add hours to it but apparently apple deletes notifications that can't be fired because of a bad date automatically.
scheduledLocalNotifications array is empty
-
06-07-2023 - |
Question
NSArray *notifs = [[UIApplication sharedApplication]scheduledLocalNotifications];
I'm trying to store all my notifications in this array but it doesn't seem to work , the array is always empty , altough notifications do trigger.
Ok something seriously retarded is happening.
I have a slider mechanism which updated the notification hour preset ( how many hours before the actual date of an event should the user get a notification).
Let's say the user originally selects the hour of the event at 2PM and the preset is 1 , so the notification will fire at 1PM , all works fine.
The slider mechanism also does the following, when it is changed , i go through all my notifications and change the firedate so it's updated accordingly . Here is the code :
-(void)updateNotifications{
NSArray notifs = [[UIApplication sharedApplication]scheduledLocalNotifications];
NSDateFormatter *dateFormatterForNsLog = [[NSDateFormatter alloc]init];
[dateFormatterForNsLog setDateStyle:NSDateFormatterFullStyle];
[dateFormatterForNsLog setTimeStyle:NSDateFormatterFullStyle];
NSString *notificationHourNew = [[NSUserDefaults standardUserDefaults]objectForKey:@"notificationHour"];
int notifHourNew = [notificationHourNew intValue];
int notifHourOld = [self.notificationHour intValue];
NSLog(@"Original notification hour is %d , and when exiting the view it is : %d",notifHourOld,notifHourNew);
int difference = notifHourOld - notifHourNew;
NSLog(@"The difference is : %d", difference);
if (difference != 0) {
[[UIApplication sharedApplication]cancelAllLocalNotifications];
for (UILocalNotification *notif in notifs) {
notif.fireDate = [NotificationHelper fireDateOfLocalNotificationForDate:notif.fireDate byAddingNumberOfHours:difference];
NSLog(@"Notification date is now:%@",[dateFormatterForNsLog stringFromDate:notif.fireDate]);
[[UIApplication sharedApplication]scheduleLocalNotification:notif];
}
}
This is triggered in viewDidDissapear.
It works in only 1 case ( which i don't understand why) , if i increase the slider value. Example : Original preset is 4 , i make it 5 ( so now the notification will fire 5 hours before the event).
If i try to modify the preset to go from 5->4 (decrease) , the array is empty (LOL) and nothing works. Why?
edit : the method i use to alter the date:
+(NSDate*)fireDateOfLocalNotificationForDate:(NSDate *)date byAddingNumberOfHours:(int)hours{
NSDate *initialDate = date;
NSDateComponents *comps = [[NSDateComponents alloc]init];
[comps setHour:+hours];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *fireDate = [calendar dateByAddingComponents:comps toDate:initialDate options:0];
return fireDate;
}
Solution