Hello, I have been able to solve the issue of receiving push notifications in ionic when app is closed/killed after struggling with it for days. It seems there are still no clear answers on the issue. Before following the steps below, ensure you have set up FCM plugin and are able to receive notifications when your app is opened.
The main issue seems to be that the getInitialPushPayload() method returns undefined. This is because you are probably calling it in your FCM.onNotification() event callback and that event will not fire when your app is killed because it is pretty impossible to do so . The code usually looks like this
FCM.onNotification().subscribe(data => {
if (data.wasTapped) {
// handle data here
console.log("received in background");
FCM.getInitialPushPayload().then( data => {
// or handle data here
console.log(data);
console.log("received in background")
}, error=> console.log(error))
} else {
console.log("received in foreground")
};
});
The above code only works when app is opened and is in foreground/background. But fails to work when app is killed/closed.
FIrst Step
Add this property “click_action”: “FCM_PLUGIN_ACTIVITY” and the below object
"data": {
"title": "title",
"body": "body"
}
to notification object. Note that the above data json object is different from the default and standard “title” and “body” fields but should ideally contain the same information for consistency.
Second step
Retrieve the data we just defined using the getInitialPushPayload() method once we are sure that the FCM plugin is ready.
I personally do this inside the getToken() method which is called after platform.ready().
getToken() {
FCM.getToken().then( token => {
// Register your new token in your back-end if you want
// backend.registerToken(token);
console.log(token);
// get push payload and display if notification was tapped
FCM.getInitialPushPayload().then( data => {
if(data) {
if(data.wasTapped) {
// we know the user launched the app by clicking on the notification
// data here contains the data object we defined earlier so you can do whatever you want with the data like navigate to a specific page etc.
console.log(JSON.parse(data));
}
}
})
});
}
That is it
FCM is quite easy to work with once you understand what is going on behind the scenes .