我需要以编程方式清除Notification Center中已显示的本地通知。在this link之后我实现了建议的解决方案,但问题是此示例中的eventArray
始终具有0个元素。当我向下滑动以显示通知中心时,我会看到之前已创建的4个通知。所以在这种情况下我希望这个数组有4个元素,但它有0个。任何想法为什么会这样?我已经尝试过iOS 8.3和9.2.1,并且两个数组都是0。
iOS有两种呈现本地通知的方式:
编辑: 以下是代码示例我是如何做到的:
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody = @"1";
localNotification.alertTitle = @"1";
localNotification.userInfo = uniqueDictIdentifier1;
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
UILocalNotification *localNotification2 = [[UILocalNotification alloc] init];
localNotification2.alertBody = @"2";
localNotification2.alertTitle = @"2";
localNotification2.userInfo = uniqueDictIdentifier2;
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification2];
....
//2 more notifications are created like this
然后有过滤所有通知的代码:
NSArray *eventArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
for (int i=0; i<[eventArray count]; i++) {
UILocalNotification* oneEvent = [eventArray objectAtIndex:i];
NSDictionary *userInfoCurrent = oneEvent.userInfo;
if ([userInfoCurrent isEqualToDictionary:uniqueDictIdentifier1]) {
[[UIApplication sharedApplication] cancelLocalNotification:oneEvent];
break;
}
}
答案 0 :(得分:0)
用于保存唯一ID的通知
NSDictionary * infoDict = @{ @"alarmUiqueId" : uID,
};
NSLog(@"%@",infoDict);
NSDateComponents *comp = [[NSCalendar currentCalendar] components:NSCalendarUnitSecond
fromDate:fireDate];
fireDate = [fireDate dateByAddingTimeInterval:-comp.second];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = fireDate;
localNotif.timeZone = [NSTimeZone localTimeZone];
localNotif.alertBody = desString;
localNotif.userInfo = infoDict;
localNotif.repeatInterval = NSCalendarUnitDay;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif]
并删除一个paritcular通知编写此代码。
NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
for(UILocalNotification *notification in notificationArray)
{
NSLog(@"%@",[notification.userInfo valueForKey:@"alarmUiqueId"]);
if ([[notification.userInfo valueForKey:@"alarmUiqueId"] isEqualToNumber: health.uniqueId])
{
[[UIApplication sharedApplication] cancelLocalNotification:notification] ;
}
}
答案 1 :(得分:0)
我的理解如下:
您无法通过scheduledNotifications
获取已通知的LocalNotification信息。
我的解决办法就是将UILocalNotification实例保留在应用程序的单例对象中,并在想要从通知中心删除时使用实例调用cancelLocalNotification
。
这可能是你的帮助吗?