以编程方式从通知托盘中删除UILocalNotification

Mr.*_*ous 12 iphone objective-c ios uilocalnotification

有没有办法以编程方式UILocalNotification从通知托盘中删除/解除.我可以取消删除通知的通知

[[UIApplication sharedApplication] scheduledLocalNotifications]
Run Code Online (Sandbox Code Playgroud)

这是我需要做的

我需要UILocalNotification在执行操作后(即在用户点击通知后)从NotificationTray中解除

编辑:我可以删除通知NSNotificationCenter.我想从通知托盘中删除特定通知.例如,用户按下清除按钮以清除属于特定应用程序的所有通知.

Mid*_* MP 16

您可以使用以下方法取消所有通

[[UIApplication sharedApplication] cancelAllLocalNotifications];
Run Code Online (Sandbox Code Playgroud)

如果要删除特定通知,可以使用userinfo通知对象,在创建本地通知时为其添加唯一ID.稍后您可以使用该ID删除本地通知.

为此,您可以使用以下代码:

NSString *notificationId = @"id_to_cancel";
UILocalNotification *notification = nil;
for(UILocalNotification *notify in [[UIApplication sharedApplication] scheduledLocalNotifications])
{
  if([[notify.userInfo objectForKey:@"ID"] isEqualToString:notificationId])
  {
     notification = notify;
     break;
  }
}
[[UIApplication sharedApplication] cancelLocalNotification:notification];
Run Code Online (Sandbox Code Playgroud)

  • 如果通知已显示为"scheduledLocalNotifications"将返回零条目(因为它不再"已安排"且已经被触发),则此方法无效.点按时删除通知的其他任何方式? (9认同)

Ant*_*tox 6

我相信我有类似的问题.当应用程序进入前台时,我尝试清除过去的通知,以从通知托盘中删除任何旧通知.

我做了类似的事情来抓取旧通知并删除它们:

NSArray *activeNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
NSArray *pastNotifications = [activeNotifications filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"firDate < %@", [NSDate date]]];
for (UILocalNotification *notification in pastNotifications) {
    [[UIApplication sharedApplication] cancelLocalNotification:notification];
}
Run Code Online (Sandbox Code Playgroud)

但是,scheduledLocalNotifications即使它们仍然出现在通知中心,似乎也不包括已经过去的日期已经过去的地点.

呼叫cancelAllLocalNotifications确实似乎也删除了过去的通知.因此,我们可以获取所有当前通知,取消所有内容,然后添加我们仍然感兴趣的内容.

// Grab all the current notifications
NSArray *activeNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];

// Clear all notifications to remove old notifications
[[UIApplication sharedApplication] cancelAllLocalNotifications];

// Add back the still relevant notifications
for (UILocalNotification *notification in activeNotifications) {
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
Run Code Online (Sandbox Code Playgroud)

此外,如果不再需要某些通知,我们可以在添加它们之前对其进行一些过滤,并且我们可以在应用程序变为活动状态时获取活动通知,将它们存储在实例变量中,并且仅在应用程序移动到时才将其添加回来的背景


Muj*_*key 2

[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
Run Code Online (Sandbox Code Playgroud)

也会做一些伎俩

但如果你没有使用 applicationIconBadgeNumber,它将不起作用,所以技巧是首先设置 applicationIconBadgeNumber :)

[[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
Run Code Online (Sandbox Code Playgroud)