2

根据AppleUILocationNotification.fireDate文档:

如果指定的值为 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;

如果我将 time(NULL)-5 更改为 time(NULL)+5,我会在此代码运行 5 秒后收到通知。使用 -5 值,我永远不会收到通知。

我知道这里的好问题需要有一个可能的明确答案,这可能会受到很多“我也是”答案的影响——所以我正在寻找的是来自 Apple 的官方(引用/链接)说这是预期的行为,或者按照文档所说的那样工作的上述代码的不同版本。

这对我的应用程序很重要,因为在某些情况下我需要通知用户警报,即使它发生在当天早些时候。我想我可以修改我的代码来检查当前时间并总是给出一个超出几秒的值——但我不确定“超出多少秒”是否真的安全,我希望它尽快发生——如果有更好的方法来获得“记录在案的行为”,也宁愿没有那个黑客。我的真实代码与上面类似,但我发布了几个通知,有些可能是过去的,有些可能是今天晚些时候,有些是明天及以后(这是用于日历应用程序)。

4

1 回答 1

3

@eselk,

我看到与您相同的行为:如果通过在 UIApplication 对象上设置属性UILocalNotification来安装它,那么过去具有fireDate的新创建的将不会触发。scheduledLocalNotifications

但是,如果使用 UIApplication 的方法UILocalNotification安装相同的对象,它将立即触发。scheduleLocalNotification

在我看来,这是一个基于scheduleLocalNotifications 文档的错误,它非常清楚地指出:

...当您设置 [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 模拟器上测试过)

于 2012-11-06T01:51:34.487 回答