Hi, folks. I’m working on an application with Ionic2 which will receive push notifications when the user turn on the notification option. The thing is the application needs to turn the notification option back off, and unsubscribe from the Google Firebase Topic Messaging when it received a push notification. I tried to unsubscribe by using the following method, but it works only when the users are using the application. It still receives the notifications when the application is running in background or phone is locked. Here is my sample code:
getNotification() {
if (localStorage.getItem('notification') == null) {
localStorage.setItem('notification', 'notifications-off');
this.notification = 'notifications-off';
} else {
this.notification = localStorage.getItem('notification');
}
this.initPushNotification();
}
initPushNotification() {
if (!this.platform.is('cordova')) {
console.warn('Push notifications not initialized. Cordova is not available - Run in physical device');
return;
}
let topics: string[] = [this.locationId];
if (this.notification == 'notifications-off') {
// Unregister from Firebase
topics = [];
}
const options: PushOptions = {
"android": {
"senderID": "SendID",
"vibrate": "true",
"sound": "true",
"iconColor": "#343434",
"topics": topics
},
"ios": {
"alert": "true",
"badge": "true",
"sound": "true"
},
windows: {}
};
const pushObject: PushObject = this.push.init(options);
pushObject.unsubscribe(this.oldLocationId);
if (this.notification == 'notifications') {
pushObject.on('registration').subscribe((data: any) => {
console.log('device token -> ' + data.registrationId);
//TODO - send device token to server
});
pushObject.on('notification').subscribe((data: any) => {
console.log('message -> ' + data.message);
//if user using app and push notification comes
if (data.additionalData.foreground) {
// if application open, show popup
let confirmAlert = this.alertCtrl.create({
title: 'Washer Now',
message: data.message,
buttons: [{
text: 'Ignore',
role: 'cancel'
}, {
text: 'View',
handler: () => {
//TODO: Your logic here
this.navCtrl.popToRoot();
}
}]
});
confirmAlert.present();
} else {
//if user NOT using app and push notification comes
//TODO: Your logic on click of push notification directly
this.navCtrl.popToRoot();
console.log('Push notification clicked');
}
});
pushObject.on('error').subscribe(error => console.error('Error with Push plugin' + error));
} else {
//Unregister the old topics
pushObject.unregister();
}
}
Any ideas for this problem?