我的应用程序计划在用户选择的不同时间向用户发送UILocalNotifications。
在这种情况下,我遇到了如何管理应用程序IconBadgeNumber的问题。
正如我们所知,您必须在创建通知时设置徽章编号。我的问题是徽章数量的状态随时可能发生变化。考虑这个场景:
1) 用户收到3个通知。
2) 用户创建一个新的通知,以便在将来的某个给定时间点提醒她。此通知携带值1加上应用程序徽章的当前值(3)。
3) 用户继续他们的业务。在业务过程中,他们通过查看或使用应用程序清除当前拥有的所有3个通知(以及徽章号码)。
4) 经过给定的时间后,通知将显示在iOS中,以及之前计算的值(如果您不记得,则为4)。
5) 应用程序徽章现在是4,尽管用户只有一个实际通知。
我上下搜索了一下,但我找不到这个问题的答案,几乎可以肯定,这个问题有一个简单的答案,我完全没有找到。我该如何解决这个难题?
由于您的应用程序无法展望未来,也无法知道您将立即处理哪些事件,以及哪些事件将"挂起"一段时间,因此有一些技巧要做:
当您的应用程序处理通知时(通过点击通知、图标…),你必须:
- 获取所有挂起通知的副本
- "重新编号"这些待处理通知的徽章编号
- 删除所有挂起的通知
- 使用更正后的徽章重新注册通知副本再次输入数字
此外,当你的应用程序注册新通知时,它必须首先检查有多少通知处于挂起状态,并使用注册新通知
badgeNbr = nbrOfPendingNotifications + 1;
看看我的代码,它会变得更清晰。我测试了这个,它肯定有效:
在你的"registerLocalNotification"方法中,你应该这样做:
NSUInteger nextBadgeNumber = [[[UIApplication sharedApplication] scheduledLocalNotifications] count] + 1;
localNotification.applicationIconBadgeNumber = nextBadgeNumber;
当你处理通知(appDelegate)时,你应该调用下面的方法,它会清除图标上的徽章,并为挂起的通知(如果有)重新编号
请注意,下一个代码适用于"顺序"注册的事件。如果要在挂起的事件之间"添加"事件,则必须首先对这些事件进行"重新排序"。我没有走那么远,但我认为这是可能的。
- (void)renumberBadgesOfPendingNotifications
{
// clear the badge on the icon
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
// first get a copy of all pending notifications (unfortunately you cannot 'modify' a pending notification)
NSArray *pendingNotifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
// if there are any pending notifications -> adjust their badge number
if (pendingNotifications.count != 0)
{
// clear all pending notifications
[[UIApplication sharedApplication] cancelAllLocalNotifications];
// the for loop will 'restore' the pending notifications, but with corrected badge numbers
// note : a more advanced method could 'sort' the notifications first !!!
NSUInteger badgeNbr = 1;
for (UILocalNotification *notification in pendingNotifications)
{
// modify the badgeNumber
notification.applicationIconBadgeNumber = badgeNbr++;
// schedule 'again'
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
}
}
@Whassaahh 的积分