2016-10-02 55 views
0

待處理通知我有下面這個函數:更新iOS中10

@objc func decrementBadges(){ 
    let center = UNUserNotificationCenter.current() 

    center.getPendingNotificationRequests(completionHandler: { (notifications) in 
     print("count", notifications.count) 
     for notification in notifications{ 
      //center.removePendingNotificationRequests(withIdentifiers: notification.title) 
      print(notification.content.badge) 
      print(notification.description) 
     } 
    }) 
} 

我試圖減小對所有懸而未決的通知徽章號碼。這可能嗎? notification.content.badge是隻讀的,我無法找出設置它的方法。

+0

所有通知標誌?你在談論應用程序圖標上的徽章是嗎? –

+0

是的,遍歷所有待處理的通知並更新該通知觸發時設置的徽章號碼。 – ianhotep

回答

2

您可能需要做的是取消您想要更改的通知,然後使用新的徽章號碼安排新通知。您可以通過從該陣列中的每個通知中獲取UNNotificationRequest標識符,然後調用
center.removePendingNotificationRequests(withIdentifiers: [request, identifiers, of, notifications, to, remove])
然後計劃更新的通知。
UNNotificationRequest.identifier文檔不說

如果您安排新通知時使用相同的標識,系統中刪除以前調度的通知,該標識符,並與新的替換它。

所以你不應該先刪除它們,但這取決於你。

+0

是的,這就是我最終做的。這是我想出的功能。 – ianhotep

+0

@objc FUNC decrementBadges(EVENTID:字符串){ 令中心= UNUserNotificationCenter.current() VAR arrayOfNotifications:[UNNotificationRequest] = [] center.getPendingNotificationRequests(completionHandler:{(通知)在 打印(「通知。 (通知。報告) let content = UNMutableNotificationContent() – ianhotep

1
@objc func decrementBadges(eventId: String){ 
    let center = UNUserNotificationCenter.current() 

    var arrayOfNotifications: [UNNotificationRequest] = [] 

    center.getPendingNotificationRequests(completionHandler: { (notifications) in 
     print("notifications.count", notifications.count) 
     for notification in notifications{ 

      print(notification.description) 

      let content = UNMutableNotificationContent() 

      content.title = notification.content.title 
      content.subtitle = notification.content.subtitle 
      content.body = notification.content.body 
      content.sound = notification.content.sound 
      content.userInfo = notification.content.userInfo 
      content.categoryIdentifier = notification.content.categoryIdentifier 

      if notification.content.badge != nil { 
       var int : Int = Int(notification.content.badge!) 
       int -= 1 
       content.badge = NSNumber(value: int) 
      } 

      let infoDict = content.userInfo as NSDictionary 

      let notificationId:String = infoDict.object(forKey: "IDkey") as! String 

      if notificationId != eventId { 
       let request = UNNotificationRequest(
        identifier: notification.identifier, 
        content: content, 
        trigger: notification.trigger 
       ) 

       arrayOfNotifications.append(request) 
      } 


     } 
    }) 

    self.clearNotifications() 

    for notification in arrayOfNotifications { 

     UNUserNotificationCenter.current().add(
      notification, withCompletionHandler: nil) 
    } 

}