Xamarin.iOS Firebase не получает push-уведомления, но получает токен - PullRequest
0 голосов
/ 21 октября 2019

Я устанавливаю push-уведомления в проекте Xamarin.Forms. Я уже сделал все для Xamarin.Forms.Android, и он работает без проблем, но у меня много проблем с частью iOS. Это даже не первый раз, когда я делаю это, но я все еще не могу понять, что происходит.

Что я сделал:
1. Включен Nuget Xamarin.Firebase.iOS.CloudMessaging v3.1.2(который не самый последний, но последний даже не создается из-за библиотечных ошибок)
2. Создайте приложение Firebase и следуйте обычной настройке, загрузили мой .p12 для push-уведомлений и добавили мой Team ID.
p12
3. Добавил мой GoogleService-Info.plist и установил его BuildAction на «BundleResource»
4. Обновил мой Info.plist
infoplist
5. Убедитесь, что мой идентификатор приложения вВ программу Apple Developer включены Push-уведомления и правильный сертификат
cert
6. Добавлен каждый фрагмент кода, который я могу связать с интерфейсами UserNotifications.IUNUserNotificationCenterDelegate, IMessagingDelegate
7. Получен мой токен из

Firebase.InstanceID.InstanceId.Notifications.ObserveTokenRefresh((sender, e) =>
            {
                var token = Messaging.SharedInstance.FcmToken;

                if (!string.IsNullOrEmpty(token))
                {

                    //AppData.Instance.TokenMobile = newToken;
                }
            });
Вернулся на консоль Firebase, создал тестовый пуш и попытался отправить его как через "Invia messagio di prova" ("Отправить сообщение"), что заставило меня указать один токен, так и через публикацию.
not1
not2

My AppDelegate.cs

    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, UserNotifications.IUNUserNotificationCenterDelegate, IMessagingDelegate
    {
        //
        // This method is invoked when the application has loaded and is ready to run. In this 
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            global::Xamarin.Forms.FormsMaterial.Init();
            LoadApplication(new App());

            Firebase.Core.App.Configure();
            // For iOS 10 data message (sent via FCM)
            Messaging.SharedInstance.Delegate = this;

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

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

            UIApplication.SharedApplication.RegisterForRemoteNotifications();

            // Handle token as you wish
            Firebase.InstanceID.InstanceId.Notifications.ObserveTokenRefresh((sender, e) =>
            {
                var token = Messaging.SharedInstance.FcmToken;

                if (!string.IsNullOrEmpty(token))
                {

                    //AppData.Instance.TokenMobile = newToken;
                }
            });


            UIApplication.SharedApplication.StatusBarHidden = true;
            UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;

            return base.FinishedLaunching(app, options);
        }

        public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
        {
        }

        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
        {
        }

        [Export("messaging:didRefreshRegistrationToken:")]
        public void DidReceiveRegistrationToken(Messaging messaging, string fcmToken)
        {
            Console.WriteLine($"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.
        }

        public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
        {
        }

        public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
        {
            //Tested
            //Messaging.SharedInstance.ApnsToken = deviceToken;
        }

        public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
        {
            var userInfo = notification.Request.Content.UserInfo;

            // With swizzling disabled you must let Messaging know about the message, for Analytics
            // Messaging.SharedInstance.AppDidReceiveMessage (userInfo);

            // Print full message.
            Console.WriteLine(userInfo);

            // Change this to your preferred presentation option
            completionHandler(UNNotificationPresentationOptions.None);
        }

        public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action boh)
        {

        }

        [Export("messaging:didReceiveMessage:")]
        public void DidReceiveMessage(Messaging messaging, RemoteMessage message)
        {

        }
    }

Я также добавил этот ключ в файл Entitlment.plist:

<dict>
    <key>aps-environment</key>
    <string>development</string>
</dict>   

На этомЯ ожидал получить что-то в своем приложении, но ничего не могу получить.
Я ставлю несколько точек останова в каждом обратном вызове, который я пытался реализовать, но ни один из них не вызывается.
Если это может быть полезно,даже метод «DidReceiveRegistrationToken» не вызывается.

1 Ответ

0 голосов
/ 21 октября 2019

Решил проблему.
Я не знаю точно, почему, но я нашел в своем GoogleService-Info.plist ключ API, отличный от того, который указан в консоли Firebase. Я обновил ключ и теперь получаю уведомления.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...