FirebasePushNotificationPlugin icon indicating copy to clipboard operation
FirebasePushNotificationPlugin copied to clipboard

How to trigger OnNotificationReceived when app is killed/terminated on iOS ?

Open youceflebid opened this issue 5 years ago • 5 comments

Hello all,

I am on iOS 13.6 with an Iphone 8 Plus. And I am trying to receive a notification while the app is killed.

While the app is killed i receive the notification with buttons but the OnNotificationReceived method is not called. In foreground or background it works great !

Here is my code :

protected override void OnStart()
        {

            App.BadgeNotification = 0;
            Xamarin.Forms.DependencyService.Get<IBadgeService>().RemoveBadge();


            CrossFirebasePushNotification.Current.OnTokenRefresh += (s, p) =>
            {
            };

            CrossFirebasePushNotification.Current.OnNotificationReceived += async (s, p) =>
            {
                if (p.Data["gcm.message_id"].ToString() != Notification)
                {
                    Notification = p.Data["gcm.message_id"].ToString();
                    try
                    {
                        if (p.Data.ContainsKey("version"))
                        {
                            App.Update = p.Data["version"].ToString();
                            await SecureStorage.SetAsync("update", App.Update);
                        }
                        if (p.Data.ContainsKey("link") && p.Data.ContainsKey("click_action") && p.Data["click_action"].ToString() == "download")
                        {
                            MainThread.BeginInvokeOnMainThread(async () =>
                            {
                                await App.Database.SaveAnswerAsync(new Answer() { Title = p.Data.ContainsKey("body") ? p.Data["body"].ToString() : "", DateOfReception = DateTime.Now, Link = p.Data["link"].ToString(), IsAttachment = true });
                                var answers = await App.Database.GetAnswersAsync();
                                App.Answers.Clear();
                                foreach (var answer in answers.OrderByDescending(a => a.ID))
                                    App.Answers.Add(answer);

                                if (App.IsSleeping)
                                {
                                    App.BadgeNotification++;
                                    DependencyService.Get<IBadgeService>().AddBadge(App.BadgeNotification);
                                }

                            });
                        }
                        else if (p.Data.ContainsKey("click_action"))
                        {
                            if (p.Data["click_action"].ToString() == "response")
                            {
                                await App.Database.SaveAnswerAsync(new Answer() { Title = p.Data["body"].ToString(), DateOfReception = DateTime.Now, IsAttachment = false });
                                var answers = await App.Database.GetAnswersAsync();
                                App.Answers.Clear();
                                foreach (var answer in answers.OrderByDescending(a => a.ID))
                                    App.Answers.Add(answer);


                                if (App.IsSleeping)
                                {
                                    App.BadgeNotification++;
                                    DependencyService.Get<IBadgeService>().AddBadge(App.BadgeNotification);
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            };

            CrossFirebasePushNotification.Current.OnNotificationAction += async (s, p) =>
            {
                try
                {
                    if (!string.IsNullOrEmpty(p.Identifier) && p.Identifier == "Open")
                    {
                        ((TabbedPage)App.Current.MainPage).CurrentPage = ((TabbedPage)App.Current.MainPage).Children[0];
                    }
                }
                catch (Exception) { }

            };

        }

youceflebid avatar Aug 19 '20 08:08 youceflebid

Hi, have you found a solution? It's the same way on Android too...

gogolon avatar Mar 14 '21 18:03 gogolon

Hello, have you fixed that somehow?

I am struggling with OnNotificationOpened event on iOS as well and I cannot figure it out... app gets opened but no way to catch the data payload... When app is in foreground/background it works as expected. When app is killed notification arrives but no event occurs, even if I tap on it.

psmoq avatar Aug 27 '21 06:08 psmoq

Hi, i think it is not possible to execute app code while iOS app is killed. I can receive the notification while the app is killed, but i can only execute my code if the user tabs the notification from the notification center. On Android i can still receive notifications when the app is swipe-killed if i instantiate the Plugin in a MainApplication.cs (a class that inherits from Application). But i didnt managed to get it work on iOS.

BFuchshofer avatar Jan 31 '22 12:01 BFuchshofer

@BFuchshofer I know it is impossible to execute the code when the app is killed - I am not expecting it at all.

The behavior you described would be desired on my side. I just want to get the notification payload when app is started after notification is tapped from notification center. Currently an event is not fired at all so I cannot get the payload even if app is started on tap. Any ideas?

psmoq avatar Feb 01 '22 15:02 psmoq

When you look at the source code you will see that the OnNotificationOpened event is fired in the Inititialize Method: https://github.com/CrossGeeks/FirebasePushNotificationPlugin/blob/95d41b4a4d65104717617b4f48ade164539fcb6b/Plugin.FirebasePushNotification/FirebasePushNotificationManager.ios.cs#L156 This method is typically called before you create the XF App: LoadApplication(new App()); in AppDelegate. And if you register the OnNotificationOpened Event in App.xaml.cs constructor the event is not fired. As a workaround you could call Inititalize twice in FinishedLaunching:

FirebasePushNotificationManager.Initialize(options);
LoadApplication(new App()); //OnNotificationOpened  is registered in ctor
var launchResult = base.FinishedLaunching(app, options); //base.FinishedLaunching calls OnStart in Application
FirebasePushNotificationManager.Initialize(options, false);
return launchResult;

AlleSchonWeg avatar Mar 02 '23 07:03 AlleSchonWeg