简体   繁体   中英

Firebase push notification receiving only when app is in foreground ios

I have integrated my app Xamarin.iOS with Firebase Cloud Messaging. Push notifications working properly when app is in foreground or i background the app & then return to the app but not working when app is in background or killed.

Here is my code

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {

            UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.LightContent;

            Firebase.Core.App.Configure();
            UNUserNotificationCenter.Current.Delegate = this;
            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
            {
                // For iOS 10 display notification (sent via APNS)

                var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
                UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
                    Console.WriteLine(granted);
                });
            }
            else
            {
                // iOS 9 or before
                var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
                var settings = UIUserNotificationSettings.GetSettingsForTypes(allNotificationTypes, null);
                UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
            }

            Messaging.SharedInstance.Delegate = this;
            UIApplication.SharedApplication.RegisterForRemoteNotifications();
             Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
            var token = Messaging.SharedInstance.FcmToken;
            Rg.Plugins.Popup.Popup.Init();
            ZXing.Net.Mobile.Forms.iOS.Platform.Init();
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());
            return base.FinishedLaunching(app, options);
        }

Methods which are working perfectly when app is in foreground

[Export("messaging:didReceiveRegistrationToken:")]
        public void DidReceiveRegistrationToken(Messaging messaging, string fcmToken)
        {
            // Monitor token generation: To be notified whenever the token is updated.

            LogInformation(nameof(DidReceiveRegistrationToken), $"Firebase registration token: {fcmToken}");

            // TODO: If necessary send token to application server.
            // Note: This callback is fired at each app startup and whenever a new token is generated.
        }

[Export("messaging:didReceiveMessage:")]
        public void DidReceiveMessage(Messaging messaging, RemoteMessage remoteMessage)
        {
            // Handle Data messages for iOS 10 and above.
            //  HandleMessage(remoteMessage.AppData);
            var notification = (NSDictionary)remoteMessage.AppData.ValueForKey(new NSString("notification"));
            var title = notification.ValueForKey(new NSString("title"));
            var text = notification.ValueForKey(new NSString("body"));
            remotenotification = true;
            ScheduleNotification(title.ToString(), text.ToString());
}
//This code is for showing notification
void ScheduleNotification(string title, string body)
        {
            // Create content
            var content = new UNMutableNotificationContent();
            content.Title = title;
            //content.Subtitle = "Subtitle";
            content.Body = body;
            content.Badge = 1;
            content.CategoryIdentifier = "notification_fv";
            content.Sound = UNNotificationSound.Default;

            // Fire trigger in one seconds
            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);

            var requestID = "customNotification";
            var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            //                      This is the line that does the trick

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => {
                if (err != null)
                {
                    // Report error
                    System.Console.WriteLine("Error: {0}", err);
                }
                else
                {
                    // Report Success
                    System.Console.WriteLine("Notification Scheduled: {0}", request);
                }
            });
        }

[Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
        public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
        {
            if (!remotenotification)
                return;
            SystemSound.Vibrate.PlayAlertSound();
            SystemSound.Vibrate.PlaySystemSound();
            completionHandler(UNNotificationPresentationOptions.Alert);
            remotenotification = false;
        }

Payload which i am receiving from FCM composer

{{
    "collapse_key" = "com.app.myApp";
    from = 933033592921;
    notification =     {
        body = for;
        e = 1;
        tag = "campaign_collapse_key_6180700435185093924";
        title = Testing;
    };
}

Can anybody tell me what i am missing here?

Issue solved: The issue was Found when i implemented this method it throws me an error no valid “aps-environment” entitlement string found for application

public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
        {
            var alert = new UIAlertView("Computer says no", "Notification registration failed! Try again!", null, "OK", null);

            alert.Show();
        }

Then i sorted this issue, it was i did't entered Entitlement.plist in my iOS Bundle Signing option -> Custom Entitlements. After adding this file now notifications are receiving (with notification payload) in all conditions (Foreground, Background and also if app has been destroyed) May be this would help somebody also :) .

        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
        {
            //Background
            completionHandler(UIBackgroundFetchResult.NewData);
        }

it worked for me to fetch notification in background.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM