Asenjo
Asenjo

Reputation: 111

IONIC 5 FCM Plugin onNotification not fired when app is killed/closed (IOS & Android)

I am stuck with a problem in both platforms with FCM plugin (https://ionicframework.com/docs/native/fcm), the problem is I can´t handle notifications when app is closed/killed, the onNotification() method isn´t fired (it works fine in background and foreground)

this.fcm.onNotification().subscribe((payload) => {
          if (payload.wasTapped) {
            console.log('Notification received in background');
          } else {
            console.log('Notification received in foreground');
          }
          console.log('Notification payload: ',payload);
  });

notification body working fine in background and foreground (both platforms):

{
 "to" : <device-key>,
"collapse_key" : "app-key",
 "notification" : {
     "body" : "body",
     "title": "title"
 },
 "data" : {"parameter":"1"},
 "android": {
    "notification": {
      "click_action": "FCM_PLUGIN_ACTIVITY"
    }
  }
}

The ionic info output for IOS environment:

Ionic:

   Ionic CLI                     : 6.11.10 (/usr/local/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.3.3
   @angular-devkit/build-angular : 0.901.12
   @angular-devkit/schematics    : 9.1.12
   @angular/cli                  : 9.1.12
   @ionic/angular-toolkit        : 2.3.3

Cordova:

   Cordova CLI       : 10.0.0
   Cordova Platforms : ios 6.1.1
   Cordova Plugins   : cordova-plugin-fcm-with-dependecy-updated: ^7.3.1

System:

   ios-sim : 8.0.2
   NodeJS  : v14.13.0 (/usr/local/Cellar/node/14.13.0/bin/node)
   npm     : 6.14.8
   OS      : macOS Catalina
   Xcode   : Xcode 12.0.1 Build version 12A7300

Upvotes: 0

Views: 1210

Answers (1)

vigamage
vigamage

Reputation: 2125

I believe your subscription is inside the constructor or inside the onInit function.

It does not matter if the app is in the foreground or the background, since the app is working, the subscription gets invoked.

But when the app is killed, how does the subscription gets invoked?. When you receive the notification, you tap on it. then only the app starts. after the app is started only, the subscription is active.

What you have to do is, invoke the fcm.getInitialPushPayload() when the app starts.

Place following inside your constructor.

this.platform.ready().then(() => {

    this.fcm.getInitialPushPayload().then((payload) => {
  
      if(payload.wasTapped) {
        console.log("Received FCM when app is closed -> ", JSON.stringify(payload));
        // call your function to handle the data
        this._handlePushNotificationData(payload);
      }                                 
      
    });

}

Now, when the app is closed, when you tap on the notification you received, the app will start and the above function will be called. Then your data will be available in the callback.

Upvotes: 4

Related Questions