c# - 仅当应用程序处于前台 ios 时才接收 Firebase 推送通知

标签 c# xamarin xamarin.ios firebase-cloud-messaging

我已将我的应用程序 Xamarin.iOS 与 Firebase 云消息传递集成。当应用程序处于前台或我将应用程序置于后台时,推送通知正常工作,然后返回到应用程序,但当应用程序处于后台或被杀死时,推送通知无法正常工作。

这是我的代码

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

当应用程序在前台运行时完美运行的方法

[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 composer 收到的有效负载

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

谁能告诉我我在这里缺少什么?

最佳答案

问题已解决: 当我实现这个方法时发现了这个问题,它抛出了一个错误 未找到应用程序的有效“aps-environment”授权字符串

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 Bundle Signing 选项 -> Custom Entitlements 中输入 Entitlement.plist。添加此文件后,现在在所有情况下(前景、背景以及应用程序已被销毁)都会收到通知(带有通知负载)可能这也会对某些人有所帮助:)。

关于c# - 仅当应用程序处于前台 ios 时才接收 Firebase 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59563658/

相关文章:

c# - Xamarin Android 上的振动

c# - 不符合键值编码(Monotouch 和 iOS 6)

iphone - AVAssetExportSession dealloc 在 iOS 4.3 中崩溃

objective-c - 协作 Objective C 和 monotuch

c# - 使用 Entity Framework 动态选择表

c# - 无法从C#中的相同类但使用不同方法访问对象属性

c# - Azure 函数异常 - 将日志写入表存储时出错 : Microsoft. Azure.Cosmos.Table.StorageException

c# - 如何将值从 C++ 主应用程序返回到 C# GUI 应用程序?

android - android xamarin中不同页面的不同自定义导航栏(操作栏)

c# - 制作两个 SharedPreferences