我在通知方面遇到了类似的问题。我实际删除的解决方案是设置一个特定的日期并且只通知一次。行 applicationIconBadgeNumber = 0 从通知列表中删除通知。徽章编号仅在用户进入应用程序时设置。对于用户还没有看到消息的情况,您可以在 applicationWillEnterForeground 中添加一个检查并显示一个与通知相同的消息的适当 UIAlertView,您可以使用 notificationArray 以类似的方式获取最后一个通知。当需要设置新的通知“isNotified”需要setValue:@"0"并进行同步。当我使用多个通知时,我会保存如下状态:
[userDefaults setValue:@"1" forKey:[NSString stringWithFormat:@"notification-%@", @"12"]];
NSInteger number = [[userDefaults objectForKey:[NSString stringWithFormat:@"notification-%@", @"12"]] integerValue];
在 MainViewController.m
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSInteger alreadyNotified = [[userDefaults objectForKey:@"isNotified"] integerValue];
if (alreadyNotified == 0) {
NSInteger seconds = 60;
NSString *message = @"Just testing!";
UILocalNotification *notification = [[UILocalNotification alloc] init];
UIUserNotificationSettings *currentSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];
BOOL allowNotif = (currentSettings.types != UIUserNotificationTypeNone);
BOOL allowsSound = (currentSettings.types & UIUserNotificationTypeSound) != 0;
BOOL allowsBadge = (currentSettings.types & UIUserNotificationTypeBadge) != 0;
BOOL allowsAlert = (currentSettings.types & UIUserNotificationTypeAlert) != 0;
if (notification)
{
if (allowNotif)
{
NSDate *now = [NSDate date];
if (seconds > 0) {
now = [now dateByAddingTimeInterval:seconds];
}
notification.fireDate = now;
notification.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
notification.repeatInterval = 0;
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"id", message, @"message", nil];
notification.userInfo = userInfo;
}
if (allowsAlert)
{
notification.alertBody = message;
}
if (allowsBadge)
{
notification.applicationIconBadgeNumber = 1;
}
if (allowsSound)
{
notification.soundName = UILocalNotificationDefaultSoundName;
}
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setValue:@"1" forKey:@"isNotified"];
[userDefaults synchronize];
}
} else {
UIApplication *app = [UIApplication sharedApplication];
NSArray *notificationArray = [app scheduledLocalNotifications];
for (int i=0; i<[notificationArray count]; i++)
{
UILocalNotification *notification = [notificationArray objectAtIndex:i];
[app cancelLocalNotification:notification];
}
}
在 AppDelegate.m
- (void)applicationWillEnterForeground:(UIApplication *)application {
application.applicationIconBadgeNumber = 0;
}