如何實現本地通知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) **
暫時沒遇到問題。。
原問題鏈接