EddyVerbruggen / nativescript-plugin-firebase

:fire: NativeScript plugin for Firebase
https://firebase.google.com
MIT License
1.01k stars 446 forks source link

onMessageReceivedCallback executes twice or never #1608

Open curtiscarlson opened 4 years ago

curtiscarlson commented 4 years ago

I have spent days trying to figure this one out and I can't. I have a navigation in my onMessageReceivedCallback and it always runs twice. It clearly navigates twice and console.logging the thing out tells me that the callback runs twice.

One thing i have tried is to not immediately run messaging.registerForPushNotifications when the app loads up, but then the callback won't run at all. Like, after I have registered for notifications and received a push token, if I close the app, and reload, I still have a firebase token, but the onMessageReceivedCallback is now gone. So, it has to be added on reload.

If a notification is received and the app is closed and you tap the notification, the app loads, it re-registers for notifications, and then runs the callback twice.

If I delay registration then the callback never runs (once the app has been closed).

I have tried to modify my code to find a workaround and I can't. Any help is much appreciated.

deftfox commented 3 years ago

Seems like this behavior exist in native also https://stackoverflow.com/questions/20569201/remote-notification-method-called-twice#answer-33778990

I found workaround for this case in nativescript-plugin-firebase. If you want to run your code only once on onMessageReceivedCallback just place all your code in

if(!message.notificationTapped) { //your code here }

This way you will process push message only once

You can also put if(message.foreground) { //your code to process push message received in foreground} else { //your code to process push message received in background}

This works both in iOS and Android so you don't need code separation.

deftfox commented 3 years ago

Actually, I was wrong in previous answer, conditions are not right, I spend some time, found right conditions and tested all 6 cases (3 on iOS and 3 on Android).

Right conditions are:

if ((message.notificationTapped && message.foreground) || (message.notificationTapped == false && message.foreground) || (message.notificationTapped && message.foreground == false) || isAndroid)
{    

 //your code here
     if ((message.notificationTapped == false && message.foreground) || (message.foreground && isAndroid)) 
     {
        //your code to process push message received in foreground
     }
     else
     {
        //your code to process push message received in background
     }

}