0

I have an app developed with Ionic 6, Capacitor and Angular. In the Push Notifications implementation, pushNotificationReceived event is trigged only when app is in foreground, on iPhone. I am getting the notification when app is in background or in foreground, but this event is NOT triggered when app is in background. Here is the code sample ...

await PushNotifications.addListener('pushNotificationReceived', async (notification: PushNotificationSchema) => {
      // update the app badge count
      const badgeCount = await this.getDeliveredNotifications();
      if (!badgeCount || badgeCount == 0) Badge.set({ count: 1 });
      else Badge.set({ count: badgeCount });
    });

private getDeliveredNotifications = async () => {
    const notificationList: DeliveredNotifications = await PushNotifications.getDeliveredNotifications();
    console.log('delivered notifications', notificationList);
    return notificationList.notifications.length;
  }

Can anyone help me with this issue? Not sure why the event is NOT triggered when app is in background. Any help is greatly appreciated. Thanks in advance.

Problem seem to be unique and I did not find anything similar happening to anyone.

Ionic Info ...enter image description here

Chandra T
  • 1
  • 2
  • Please post your `"PushNotifications": {}` from capacitor.config.json. For example: do you have `"presentationOptions": ["badge", "sound", "alert"]` –  Apr 19 '23 at 17:16
  • Here it is ... >>>> "PushNotifications": { "presentationOptions": ["badge", "sound", "alert"] }, – Chandra T Apr 19 '23 at 17:18
  • So not that :) Maybe something here helps? https://stackoverflow.com/questions/62533419/capacitor-ionic-handling-push-notification-in-background-or-when-app-was-killed –  Apr 19 '23 at 17:36
  • Nope. I am still stuck ... :( – Chandra T Apr 20 '23 at 08:30

2 Answers2

0

To receive background notifications, you must add the remote notifications background mode to your app in XCode. In the Signing & Capability tab, add the Background Modes capability, then select the Remote notification checkbox (Source).

Also, be sure to include the content_available key in the payload.
From the Firebase documentation:

On Apple platforms, use this field to represent content-available in the APNs payload. When a notification or message is sent and this is set to true, an inactive client app is awoken, and the message is sent through APNs as a silent notification and not through FCM. Note that silent notifications in APNs are not guaranteed to be delivered, and can depend on factors such as the user turning on Low Power Mode, force quitting the app, etc. On Android, data messages wake the app by default. On Chrome, currently not supported.

RGe
  • 1,181
  • 1
  • 10
  • 19
  • Background Mode -> Remote Notifications capability is added ....but no effect ... capacitor plugin does not seem to support notifications when app is in background. – Chandra T Apr 22 '23 at 17:43
  • I have not tested the official plugin so I can't confirm your assumption but I use push notifications in background on iOS with ` @capacitor-firebase/messaging` and it works. Disclaimer: I am the maintainer of ` @capacitor-firebase/messaging`. – RGe Apr 23 '23 at 05:11
  • Super! I will try this plugin and see how that goes. – Chandra T Apr 24 '23 at 04:30
  • Shifting to @capacitor-firebase/messaging worked, as I expected it to, on android 13 :), but not on Android 10 (not sure why!). I am yet to test it on iOS as xcode is still updating! (takes really long time). Thank you so much. Sincerely appreciate your help!. – Chandra T Apr 24 '23 at 11:30
  • Great, let me know if you have any problems. The plugin should also work on Android 10. I have several customers using this plugin on Android 10. – RGe Apr 24 '23 at 12:08
  • I tried the same on iOS but without any luck. I am getting the push notification but badge count does not get updated. I have a feeling that the payload is impacting it. Payload currently is this (sorry abt format) : `{ to: '', notification: { title: 'Test Notification', body: "Msg to the mobile app", aps: { alert: { "title": "New msg", "body": "checks" }, badge: 1 } }, data: { serviceId: 1, senderId: 85 }, badge: 1 };` – Chandra T Apr 26 '23 at 17:58
  • I just tested it with this demo app: https://github.com/robingenz/capacitor-firebase-plugin-demo This is the payload I used: `{ "data": { "my_custom_key": "my_custom_value", "my_custom_key2": false }, "content_available": true, "to": "..." }` It worked without problems. Make sure you use `content_available`. – RGe Apr 27 '23 at 03:35
  • Yep. Adding content_available key did the trick on iOS. :) Thank you so much. – Chandra T Apr 27 '23 at 04:05
-1

The pushNotificationReceived listener should be called even when the app is in background, but on Android the notification may not appear if you don't force it to be shown. This can be done using a local notification.

Register notification received listener:

await PushNotifications.addListener(
  'pushNotificationReceived',
  async (notification: PushNotificationSchema) => {

    // If the app is in background, this callback is only called for DATA messages
    const isPushNotification = !!notification.title || !!notification.body;

    // Android: check if this is a push notification
    if (isPushNotification) {
      if (isPlatform('android') {
        sendAndroidForegroundNotification(notification);
      }
      handleNotification(notification);
    }
  }
);

Method to send a local notification when the application is in background:

sendAndroidForegroundNotification(notification: PushNotificationSchema) {
  const at = new Date(Date.now() + 1000); // A second after
  LocalNotifications.schedule({
    notifications: [{
      title: notification.title ?? '',
      body: notification.body ?? '',
      id: at.getMilliseconds(),
      schedule: { at },
      extra: notification,
      channelId: 'pop-notifications'
    }]
  });
}

Method to execute when a notification is received (I am supposing that you can simply increment your counter):

const handleNotification = (notification: PushNotificationSchema) => {
  Badge.set({ count: Badge.get() + 1 });
}
gsim
  • 128
  • 7
  • Thanks @gsim. Like I mentioned, the pushNoficationReceived event is NOT getting fired when the app is in background. Hence badge count is not updated. That is the problem that I need a solution for. Event is registered and is working the same way in both iOS and Android. I am ok if the notification does not show when the app is in foreground. – Chandra T Apr 22 '23 at 15:26
  • @ChandraT can you please post your @capacitor/push-notifications version? You can also check if your notification data includes "android_channel_id": "pop-notifications" in the "notification" element for Android notifications and "badge": 1 for iOS notifications – gsim Apr 24 '23 at 07:15
  • @capacitor/push-notifications version is 4.1.2 and data does include badge but not the others you mentioned. data object has "aps" object though. – Chandra T Apr 24 '23 at 11:27