如何实现本地通知badgenumber自动增加
实现自动增加前提是非重复的本地通知。
几个要点:
1.在你自定义的的注册本地通知方法内,新的通知badgenumber需要通过当前存在的scheduled本地通知数量来确定。(通过后面renumberBadgesOfPendingNotifications方法也能重新分配该badgenumber)
let badgeNbr = UIApplication.sharedApplication().scheduledLocalNotifications?.count ?? 0
let nextBadgeNbr = badgeNbr + 1
yourLocalNotification.applicationBadgeNumber = nextBadgeNbr
2.当本地通知被你点击处理/进入APP的时候,你需要重新分配scheduled的本地通知。
func renumberBadgesOfPendingNotifications() {
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
let pendingNotifications = UIApplication.sharedApplication().scheduledLocalNotifications
if (pendingNotifications?.count > 0) {
UIApplication.sharedApplication().cancelAllLocalNotifications()
print(UIApplication.sharedApplication().scheduledLocalNotifications)
let badgeNbr = 0
for noti in pendingNotifications! {
let temp = badgeNbr + pendingNotifications!.indexOf(noti)! + 1
noti.applicationIconBadgeNumber = temp
// schedule 'again'
UIApplication.sharedApplication().scheduleLocalNotification(noti)
}
}
}
3.你可能会想到renumberBadgesOfPendingNotifications()假如程序内新增了本地通知,那么获得的notification并不是按照时间排序的,因而最好再加一个排序。
func renumberBadgesOfPendingNotifications() {
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
let notifications = UIApplication.sharedApplication().scheduledLocalNotifications
if (notifications?.count > 0) {
let pendingNotifications = notifications?.sort({
return $0.fireDate!.compare($1.fireDate!) == NSComparisonResult.OrderedDescending ? false : true
})
UIApplication.sharedApplication().cancelAllLocalNotifications()
let badgeNbr = 0
for noti in pendingNotifications! {
let temp = badgeNbr + pendingNotifications!.indexOf(noti)! + 1
noti.applicationIconBadgeNumber = temp
// schedule 'again'
UIApplication.sharedApplication().scheduleLocalNotification(noti)
}
}
}
然后把上面方法加入
**func applicationDidBecomeActive(application: UIApplication) **
暂时没遇到问题。。
原问题链接