有时我的应用程序的本地通知会被触发(显示)两次。我没有使用模拟器,而是使用真实设备。我一直试图获得一个重现步骤,但我无法做到。每次我使用断点/nslog 完成该过程时,我总是会收到 1 个安排好的通知。有了这个,我假设我只会显示/触发 1 个通知。但是,有时我会收到两个通知。我已经在互联网上搜索了答案,但我无法获得太多信息。这里有人经历过同样的事情吗?你是如何解决问题的?
- (void)scheduleAllNotifications
{
if (_isEnabled && [[NSUserDefaults standardUserDefaults] boolForKey:NotificationsUserDefaultsKey]) {
[self updateFireDates];
for (NSDate *fireDate in fireDates) {
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = fireDate;
notification.alertBody = @"Message";
notification.alertAction = @"View";
notification.soundName = @"notificationsound.mp3";
[notifications addObject:notification];
[[UIApplication sharedApplication]scheduleLocalNotification:notification];
}
}
}
- (void)cancelAllNotifications
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[notifications removeAllObjects];
}
- (void)updateFireDates
{
[fireDates removeAllObjects];
NSDate *now = [NSDate date];
NSDate *fireDate = [NSDate dateWithTimeInterval:THREEDAYS sinceDate:now];
if (fireDate){[fireDates addObject:fireDate];}
}
每次应用程序变为活动状态时都会调用 cancelAllNotifications 每次应用程序退出活动时都会调用 shceduleAllNotifications