I am working on an Ionic FCM push notification, In this, our requirement is to add a custom notification sound on receive notifications.
For this we have done this code:
app.component.ts file
import { Component } from '@angular/core';
import { NavController, Platform } from '@ionic/angular';
import { FCM } from 'cordova-plugin-fcm-with-dependecy-updated/ionic/ngx';
import { INotificationPayload } from 'cordova-plugin-fcm-with-dependecy-updated';
import { Push } from '@ionic-native/push/ngx';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
})
export class AppComponent {
public hasPermission: boolean;
public token: string;
public pushPayload: INotificationPayload;
constructor(private platform: Platform, private fcm: FCM, private nav: NavController,
private push: Push) {
this.createChannel();
this.setupFCM();
}
createChannel() {
// to check if we have permission
this.push.hasPermission()
.then((res: any) => {
if (res.isEnabled) {
console.log('We have permission to send push notifications');
} else {
console.log('We do not have permission to send push notifications');
}
});
// Create a channel (Android O and above). You'll need to provide the id, description and importance properties.
this.push.createChannel({
description: 'General Notifications',
id: 'my_channel_01',
importance: 5,
sound: 'shotgun.wav',
vibration: true,
visibility: 1,
badge: false
}).then(() => console.log('Channel created'));
// Return a list of currently configured channels
this.push.listChannels().then((channels) => console.log('List of channels', channels));
}
async setupFCM() {
await this.platform.ready();
console.log('FCM setup started');
if (!this.platform.is('cordova')) {
return;
}
console.log('In cordova platform');
console.log('Subscribing to token updates');
this.fcm.onTokenRefresh().subscribe((newToken) => {
this.token = newToken;
console.log('onTokenRefresh received event with: ', newToken);
});
console.log('Subscribing to new notifications');
this.fcm.onNotification().subscribe((payload) => {
if (payload.wasTapped) {
console.log('Received in background');
this.nav.navigateForward([payload.route], { animated: true });
console.log(payload.route);
} else {
console.log('Received in foreground');
};
this.pushPayload = payload;
console.log('onNotification received event with: ', payload);
});
this.hasPermission = await this.fcm.requestPushPermission();
console.log('requestPushPermission result: ', this.hasPermission);
this.token = await this.fcm.getToken();
console.log('getToken result: ', this.token);
localStorage.setItem('token', this.token);
this.pushPayload = await this.fcm.getInitialPushPayload();
console.log('getInitialPushPayload result: ', this.pushPayload);
}
}
To send notifications as we know, we can send from the firebase console, from the manual code, and using postman.
Way 1 Postman:
A URL I used in postman request: https://fcm.googleapis.com/fcm/send
Body part of code or called it json object is here:
{
"to": "fPrZ1gnPKdg:APA91bGfUWgbrfZyZdzGy6qMjY2QhR0OVCeRfuwCRXMI0Q0fsT347HWAxIzwbv8EbFrXj8X2HbrwJakATgqFlr9ZQ_1TJMyW-8i6nOMrRf-6QPoPjxz8l_kj61dsydnQDbgh8GwUKLX9",
"collapse_key": "type_a",
"notification": {
"body": "Body of Your Notification",
"title": "Title of Your Notification",
"sound": "shotgun.wav",
"channelId": "my_channel_01",
"click_action": "FCM_PLUGIN_ACTIVITY"
},
"data": {
"body": "Hello world",
"title": "Title",
"sound": "shotgun.wav",
"route": "/tabs/tab2",
"channelId": "my_channel_01",
},
"priority": "high"
}
Way 2 Manually Request using httpClient
postNoti() {
const body = {
to: this.token,
collapse_key: 'type_a',
notification: {
body: 'Body of Your Notification',
title: 'Title of Your Notification',
sound: 'shotgun.wav',
channelId: 'testchannel1',
click_action: 'FCM_PLUGIN_ACTIVITY'
},
data: {
body: 'Hello world',
title: 'Title',
sound: 'shotgun.wav',
route: this.pathName
},
priority: 'high'
};
const headers = new HttpHeaders({
Authorization: 'key=AAAA8QvR4ds:APA91bHkTOY65qN8fPE3uk2Y7RkohTJc7VTm9j_JeWHj5xXYAV7ryxZ_p7O6z9dn_-XP9n2PuvD9A406ElsQB2NEKV58QehAv109fuTkcYwCcoyzPokQut4RCzFl5ICWfadeUm6Cmw5s',
'Content-Type': 'application/json',
});
setTimeout(() => {
this.httpClient
.post('https://fcm.googleapis.com/fcm/send', body, { headers })
.subscribe((res) => {
console.log(res);
}, (err) => {
console.log(err);
});
}, 10000);
}
Here in this code, I have added a timeout, I used a timeout to send notifications because when our app is open and notification receive it won’t show in the notification bar. So after I clicking on the sendNoti() function I am closing the app so I can see notification received.
Here in this Questions on the ionic forum I took as a reference and created a channel using the Ionic push plugin but still I am not getting sound.
I am tried 3 days but didn’t solve my issue. Please help me or guide me to solve this. If anyone needs more details comment it, I will share. Thank you in advance.