According to Apple docs on UILocationNotification.fireDate:
If the specified value is nil or is a date in the past, the
notification is delivered immediately.
I am not seeing this behavior when using a date in the past. Is it just me, or are others seeing this as well?
Here is my code:
NSMutableArray *notifications = [NSMutableArray array];
UILocalNotification* alarm = [[UILocalNotification alloc] init];
alarm.fireDate = [NSDate dateWithTimeIntervalSince1970:time(NULL)-5];
alarm.repeatInterval = 0;
alarm.soundName = @"alarm.caf";
alarm.alertBody = @"Test";
alarm.alertAction = @"Launch";
NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] init];
[userInfo setValue:[NSNumber numberWithInt:10] forKey:@"PsID"];
alarm.userInfo = userInfo;
notifications = [NSArray arrayWithObject:alarm];
UIApplication *app = [UIApplication sharedApplication];
app.scheduledLocalNotifications = notifications;
If I change the time(NULL)-5 to time(NULL)+5 I get the notification 5 seconds after this code runs. With the -5 value, I never get the notification.
I know good questions here need to have a possible definite answer and this could be subject to a lot of “me too” answers — so what I’m looking for is something official (quote/link) from Apple saying this is expected behavior, or different version of the above code that works as the docs say it should.
This is important for my application because in some cases I need to notify the user of an alarm even if it happened earlier in the day. I suppose I could modify my code to check the current time and always give a value a few seconds beyond that — but I’m not sure “how many seconds beyond” is really safe, and I would like it to happen ASAP — also rather not have that hack if there is a better way to get “documented behavior”. My real code is similar to above, but I am posting several notifications, some might be in the past, some later today, some tomorrow and beyond (this is for a calendar application).
@eselk,
I see the same behavior as you: a newly-created
UILocalNotificationthat has a fireDate in the past will NOT fire if it is installed by setting thescheduledLocalNotificationsproperty on the UIApplication object.However, if the same
UILocalNotificationobject is installed using UIApplication’sscheduleLocalNotificationmethod, it will fire immediately.Seems to me to be a bug based on the documentation for scheduledLocalNotifications, which states pretty clearly that:
Given that this doesn’t seem to be the case, the workaround is to call scheduleLocalNotification if your application logic requires that notifications that are scheduled in the past need to be presented to the user.
(I tested this on the iOS 6 simulator)