Firebase推送通知仅在应用程序位于前台ios中时接收

Firebase推送通知仅在应用程序位于前台ios中时接收

本文介绍了Firebase推送通知仅在应用程序位于前台ios中时接收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将我的应用程序Xamarin.iOS与Firebase Cloud Messaging集成在一起.当应用程序处于前台或后台运行时,推送通知可以正常工作然后返回到应用程序,但当应用程序在后台或被杀死时无法正常工作.

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.

这是我的代码

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;
        }

我从FCM作曲家那里收到的有效载荷

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?

推荐答案

问题已解决:当我实现此方法时发现了问题,这使我出错找不到适用于应用程序的有效"aps-environment"授权字符串

Issue solved:The issue was Found when i implemented this method it throws me an errorno 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();
        }

然后我对这个问题进行了排序,原因是我没有在我的iOS捆绑签名选项->自定义权利中输入Entitlement.plist.添加此文件后,现在在所有情况下(前景,背景以及应用程序已被破坏)都可以接收到通知(带有通知有效负载),也许这也会对某人有所帮助:).

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 :) .

这篇关于Firebase推送通知仅在应用程序位于前台ios中时接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 13:12