2016-10-02 82 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) 
    } 

}