Ibrahim
Ibrahim

Reputation: 1903

Dismissing notifications on iOS

I am sending push notifications on iOS, and I can receive and display them correctly. I want to be able to dismiss notifications that have been read server-side (e.g. on a different device) so I am trying to send a custom payload with a badge counter update, that specifies what notification IDs to remove. I then use removeDeliveredNotifications on the IDs I get. However, it doesn't seem to be working. I am setting the identifier using the apns-collapse-id header and I do see that reflected on the client side. Any ideas what I might be doing wrong?

  func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
  ) {
    let customPayload = notification.request.content.userInfo
    if let dismissedNotifications = customPayload["dismissed_notifications"] as? [String] {
      center.removeDeliveredNotifications(withIdentifiers: dismissedNotifications)
    }

    completionHandler([.banner, .sound, .badge])
  }

I've also tried looking for the notification IDs in getDeliveredNotifications and the notification IDs I am sending do in fact correspond to received notifications. But this also does not result in the notifications getting dismissed on the device.

      center.getDeliveredNotifications(completionHandler: { notifications in
        var identifiersToRemove: [String] = []
        for notification in notifications {
          if dismissedNotifications.contains(notification.request.identifier) {
            identifiersToRemove.append(notification.request.identifier)
          }
        }
        center.removeDeliveredNotifications(withIdentifiers: identifiersToRemove)
      })

Upvotes: 0

Views: 25

Answers (0)

Related Questions