根据UILocationNotification.fireDate
上的Apple docs:
如果指定的值为nil或者是过去的日期,则为 通知立即发送。
过去使用日期时,我没有看到此行为。它只是我,还是其他人也看到了这一点?
这是我的代码:
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;
如果我将时间(NULL)-5更改为时间(NULL)+5,我会在此代码运行5秒后收到通知。使用-5值,我从未收到通知。
我知道这里的好问题需要有一个明确的答案,这可能会受到很多“我也是”的答案 - 所以我正在寻找的是官方的(引用/链接) Apple说这是预期的行为,或上述代码的不同版本,就像文档所说的那样。
这对我的应用程序很重要,因为在某些情况下,我需要通知用户警报,即使它发生在当天早些时候。我想我可以修改我的代码以检查当前时间并且总是给出一个超过几秒的值 - 但是我不确定“超出多少秒”是非常安全的,我希望它尽快发生 - 如果有更好的方法来获得“记录在案的行为”,也可能没有那种黑客攻击。我的真实代码与上面类似,但是我发布了几个通知,有些可能是过去的,有些是今天的,有些是明天和更长的通知(这是针对日历应用程序)。
答案 0 :(得分:3)
@eselk,
我看到的行为与您相同:过去创建的 fireDate 的新创建的UILocalNotification
如果安装了 ,则不会触发 UIApplication对象上的scheduledLocalNotifications
属性 。
但是,如果使用UIApplication的UILocalNotification
方法安装相同的scheduleLocalNotification
对象,则 会立即触发。
我觉得这是一个基于the documentation for scheduledLocalNotifications的错误,它非常清楚地表明:
...设置[scheduledLocalNotifications]属性时,UILocalNotification 通过调用替换所有现有通知 cancelLocalNotification:然后调用scheduleLocalNotification: 每个新通知。
鉴于情况似乎并非如此,如果您的应用程序逻辑要求将过去安排的通知呈现给用户,则解决方法是调用scheduleLocalNotification。
UILocalNotification *ln = [[UILocalNotification alloc]init];
[ln setFireDate:[NSDate dateWithTimeIntervalSinceNow:-2]]; // two seconds ago
// ...
// the following line works as expected - the notification fires immediately
[application scheduleLocalNotification:ln]; // Using this line works as expected
// using the following does NOT work as expected - the notification does not fire
//application.scheduledLocalNotifications = [NSArray arrayWithObject:ln];
(我在iOS 6模拟器上测试了这个)