Rob
Rob

Reputation: 4234

iOS : How to remove remote notifications if app is not active?

I want to clear remote notifications so they don't add up in the Notification Center (like when you get a video call in WhatsApp or Messenger, only the last notification is displayed).

I tried to call (in didReceiveRemoteNotification):

let center = UNUserNotificationCenter.current()
center.removeDeliveredNotifications(withIdentifiers: ["notification_identifier"])

But it gets called only if the app is active. How can I do this if the app is in another state?

Thanks for your help.

Upvotes: 1

Views: 907

Answers (1)

Rob
Rob

Reputation: 4234

After some research and thanks to Paulw1's answer, I found out there are two ways of doing this:

Remote only

Notifications can be collapsed remotely, you only have to send the notification with apns-collapse-id as a request header. Please note that it's only supported in HTTP/2 though. More information here.

Silent remote + local notification

The other way consists in sending a silent remote notification, with this kind of payload:

{
  "type": "notification_type",
  "aps" : {
    "content-available": 1
  }
}

It will call didReceiveRemoteNotification even if the app's state is inactive or background. Then, I create a local notification request (needs using UserNotifications, available from iOS10) :

let content = UNMutableNotificationContent()
content.body = "Notification message"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.25, repeats: false)
let request = UNNotificationRequest(identifier: "identifierToUpdate", content: content, trigger: trigger)
self.center.add(request, withCompletionHandler: nil)

The key to update the previous notification is to use the same request identifier.

Upvotes: 1

Related Questions