I am trying to implement FCM to send notifications to app users using Firebase Cloud Messaging. Though, I am unable to receive any notifications on my phone while debugging the app.
I am trying to explicitly send the request using postman on, https://fcm.googleapis.com/fcm/send. This is the following request:
{
"registration_ids": [
"my_random_device_ids"
],
"notification": {
"title": "New request",
"body": "Your action required to accept.",
"content_available": false,
"priority": "high",
"sound": "default",
"click_action": "FCM_PLUGIN_ACTIVITY"
},
"data": {
"key": "value"
}
}
This is my code to receive the notification in the application:
this.fcm.getToken().then(
(token) => {
console.log(token);
},
(err) => {
console.log("FCM", err);
}
);
this.fcm.onNotification().subscribe(data => {
console.log(data);
});
this.fcm.onTokenRefresh().subscribe(async token => {
var deviceType = this.platform.is('android') ? 'Android' : 'iOS'
var deviceDetails = { deviceID: this.deviceUUID, deviceToken: token, deviceType: deviceType };
await this.authService.insertUpdateDeviceToken(deviceDetails);
});
I receive the notification in the background, regardless of declaring this.fcm.onNotification()
.
Also, when I declare it, it doesn't log anything, which means it is not working. Is there a way to tackle this?
I have found a solution. It is similar to this but, uses the main package instead of @ionic-native/fcm
wrapper library.
The working code is as follows, to implement fcm, in an ionic project built over angular.
In cmd[your project directory]
ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated@7.3.1
Now, please make sure in your projects, within plugins folder, a folder named cordova-plugin-fcm-with-dependecy-updated
is present and within it, there is a sub folder ionic
and within this sub folder there is another sub folder ngx
.
Now, you can use it in your code, I use it in app.component.ts
import { FCM } from 'cordova-plugin-fcm-with-dependecy-updated/ionic/ngx';
// Initialise in constructor
.
.
.
.
this.fcm.getToken().then(function(token) {
console.log(token);
}).catch(err) {
console.log(err, 'Unable to get token');
});
this.fcm.onNotification().subscribe((data: any) => {
console.log(data);
});
this.fcm.onTokenRefresh(). subscribe (async token => {
console.log(token);
});
Now, it works properly. You can try sending a notification to on the token you receive.