Dismissing iOS push notifications remotely

2019-02-10 07:36发布

问题:

The Gmail app for iOS is able to receive push notifications while the app is not running (as most email apps do).

However, it is also able to clear all Gmail push notifications from the device when the unread count of the user's Inbox becomes zero, even if the app is not running.

Here is an example sequence: 1. Receive a new email in your Gmail account. 2. The iOS device displays a notification for the new message. 3. Go to the Gmail website and open the message (marking the message as "read"). 4. The notification on the iOS device is dismissed.

Note: [[UIApplication sharedApplication] scheduledLocalNotifications] only provides local notifications, i.e. those that were created within the iOS app itself.

As far as Apple's documentation for APNS describes, there is no way to remotely launch an app into the background, and there is no way to dismiss a remote notification.

So, how does the Gmail iOS app make this work?

回答1:

I was able to clear all of my push notifications as well by pushing this payload, using Parse. I'm guessing as long as you supply content-available and badge, you should be able to do the same. I didn't have to write any other code in the AppDelegate, but I did have to turn on push notifications in the projects target capabilities.

curl -X POST \
-H "X-Parse-Application-Id: xxxxxxxxxxx" \
-H "X-Parse-REST-API-Key: xxxxxxxxxx" \
-H "Content-Type: application/json" \
-d '{
       "data": {
         "content-available": "1",
         "badge":"0",
         "sound":""
       },
       "where": {"something":"something_else"}
     }' \
https://api.parse.com/1/push


回答2:

There's a 'silent push' feature in iOS that allows your app to wake up and update itself in the background upon receipt of a UI-less push notification.

Session 713 at WWDC 2014 described this at length:

Silent notifications, they are just push payloads that are sent from your APNs server that, instead of presenting a user notification like an alert or a sound or a badge on the screen, iOS, when it receives that push, will instead wake up your app in the background so that your app can do some background image processing or information processing.

In this case, your app is fetching content from a server In this case, your app is fetching content from a server so that the next time the user happens to tap on your app icon and bring it to the foreground, that information is there and ready so nobody has to wait for a loading spinner to complete and all that other stuff.



回答3:

Try this if badge number is already set,

[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

or try this if not set

[[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

This would clear your push notifications and local notification.