Xamarin表单:推送通知未收到到ios设备

时间:2019-06-25 04:37:17

标签: xamarin.forms xamarin.ios firebase-cloud-messaging

我做了以下事情:

  1. 在FCM控制台中创建一个项目,并将ios项目添加到其中。
  2. 下载了GoogleService-Info.plist,并将其添加到xamarin表单ios项目目录中,并将构建操作设置为Bundlesource
  3. 在Info.plist上启用了远程通知后台模式。
  4. 在应用的Info.plist文件中添加了FirebaseAppDelegateProxyEnabled,并将其设置为“否”。
  5. 创建了配置文件和分发证书,并将其安装到钥匙串访问中。另外,将这些证书映射到项目选项中。
  6. 在FCM控制台中上传了.p12证书。
  7. AppDelegate.cs中添加了用于处理推送通知的代码。

我的代码:

    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, IUNUserNotificationCenterDelegate
    {
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App("",""));
            RequestPushPermissionsAsync();
            _launchoptions = options;
            // Register your app for remote notifications.
        if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            // iOS 10 or later
            var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
            UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
                Console.WriteLine(granted);
            });

            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.Current.Delegate = this;

            // For iOS 10 data message (sent via FCM)
            //Messaging.SharedInstance.RemoteMessageDelegate = this;
        }
        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();
            return base.FinishedLaunching(app, options);
        }
        NSDictionary _launchoptions;
        public override void OnActivated(UIApplication uiApplication)
        {
            base.OnActivated(uiApplication);
            if (_launchoptions != null && _launchoptions.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
            {
                var notfication = _launchoptions[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary;
                PresentNotification(notfication);
            }
            _launchoptions = null;
        }

        async Task RequestPushPermissionsAsync()
        {
            var requestResult = await UNUserNotificationCenter.Current.RequestAuthorizationAsync(
                 UNAuthorizationOptions.Alert
                | UNAuthorizationOptions.Badge
                | UNAuthorizationOptions.Sound);

            bool approved = requestResult.Item1;
            NSError error = requestResult.Item2;
            if (error == null)
            {
                if (!approved)
                {
                    Console.Write("Permission to receive notification was not granted");
                    return;
                }

                var currentSettings = await UNUserNotificationCenter.Current.GetNotificationSettingsAsync();
                if (currentSettings.AuthorizationStatus != UNAuthorizationStatus.Authorized)
                {
                    Console.WriteLine("Permissions were requested in the past but have been revoked (-Settings  app)");
                    return;
                }
                UIApplication.SharedApplication.RegisterForRemoteNotifications();
            }
            else
            {
                Console.Write($"Error requesting permissions: {error}.");
            }
        }

        public async override void RegisteredForRemoteNotifications(
        UIApplication application, NSData deviceToken)
    {
        //if (deviceToken == null)
        //{
        //    // Can happen in rare conditions e.g. after restoring a device.
        //    return;
        //}

        //Console.WriteLine($"Token received: {deviceToken}");

        // Get current device token
        var DeviceToken = deviceToken.Description;
        if (!string.IsNullOrWhiteSpace(DeviceToken))
        {
            DeviceToken = DeviceToken.Trim('<').Trim('>');
        }

        Console.WriteLine($"deviceToken received: {deviceToken}");
        Console.WriteLine($"DeviceToken received: {DeviceToken}");

        // Get previous device token
        var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");

        // Has the token changed?
        if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(DeviceToken))
        {
            //TODO: Put your own logic here to notify your server that the device token has changed/been created!
        }

        // Save new device token
        NSUserDefaults.StandardUserDefaults.SetString(DeviceToken, "PushDeviceToken");

        await SendRegistrationToServerAsync(DeviceToken);
    }

        async Task SendRegistrationTokenToMainPRoject(NSData deviceToken)
        {
            MessagingCenter.Send<object, string>(this, "fcmtoken", deviceToken.ToString());
        }

        public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
        {
            Console.WriteLine($"Failed to register for remote notifications: {error.Description}");
        }

        public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo,
            Action<UIBackgroundFetchResult> completionHandler)
        {
            PresentNotification(userInfo);
            completionHandler(UIBackgroundFetchResult.NoData);
            try
            {
                UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
                NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
                var message = (aps[new NSString("webContentList")] as NSString).ToString();
                LoadApplication(new App("", message));
            }
            catch (Exception ex)
            {
                //LogInfo.ReportErrorInfo(ex.Message, ex.StackTrace, "AppDelegate-DidReceiveRemoteNotification");
            }
        }

        void PresentNotification(NSDictionary userInfo)
        {
            NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;

            var msg = string.Empty;

            if (aps.ContainsKey(new NSString("alert")))
            {
                msg = (aps[new NSString("alert")] as NSString).ToString();
            }
            if (string.IsNullOrEmpty(msg))
            {
                msg = "(unable to parse)";
            }
            MessagingCenter.Send<object, string>(this, App.NotificationReceivedKey, msg);
        }
    }

我在ios部分中没有使用任何NuGet软件包。将项目运行到设备中时,FCM令牌生成部分正在运行,我可以在VS控制台上看到fcm令牌。我试图从邮递员向设备发送测试通知,但收到InvalidRegistration错误。

邮递员回复

{
    "multicast_id": 8754155136812875313,
    "success": 0,
    "failure": 1,
    "canonical_ids": 0,
    "results": [
        {
            "error": "InvalidRegistration"
        }
    ]
}

邮递员尸体

 {
    "to" : "d20ad003 7473bfba 85dffc33 1534decf b4b886f1 c738878f fd7f2c60 d9dabc36",
 "collapse_key" : "type_a",
 "data" : {
     "body" : "Body of Your Notification in Data",
     "title": "Title of Your Notification in Title",
     "key_1" : "Value for key_1",
     "key_2" : "Value for key_2"
 },
 "notification" : {
     "body" : "Body of Your Notification",
     "title": "Title of Your Notification",
     "sound": "default",
     "content_available" : true
 }
}

我已经完成了android part的实现,并且在从邮递员处推送时收到通知。但是在ios部分出现InvalidRegistration错误,并且在我的ios设备上未收到任何通知。

对于此实现,我关注this youtube视频,完整的源代码为here

任何人都建议解决此问题的方法。

谢谢。

更新

我创建了一个示例项目和一个邮递员收藏,并将其添加到我的google folder中。

Postman集合包含2个REST API,一个用于Android设备,另一个用于ios设备

如果您导入邮递员集合并运行Android REST API,我将收到通知,因为我已在其中添加了设备FCM令牌。但是,在邮递员中运行ios REST API时,邮递员将返回InvalidRegistration错误。

请仔细阅读示例项目,请给我一个解决方案?

1 个答案:

答案 0 :(得分:1)

我已经审查并可以解决此问题。

  1. 在iOS项目中安装插件Xamarin.Firebase.iOS.CloudMessaging。
  2. AppDelegate类需要从IUNUserNotificationCenterDelegate和IMessagingDelegate接口继承。
  3. 包括Firebase.Core.App.Configure();注册远程通知之前,请使用FinishedLaunching方法。
  4. 然后您可以添加注册远程通知代码(您可以从给定的链接中获取代码)。
  5. 您需要设置用户通知委托和消息共享即时委托(UNUserNotificationCenter.Current.Delegate = this; //对于iOS 10显示通知(通过APNS发送)和Messaging.SharedInstance.Delegate = this;)。
  6. 包括具有相应属性的DidReceiveRegistrationToken和DidReceiveMessage方法

请参阅此AppDelegate类以获取更多信息,https://github.com/xamarin/GoogleApisForiOSComponents/blob/master/Firebase.CloudMessaging/samples/CloudMessagingSample/CloudMessagingSample/AppDelegate.cs

相关的Xamarin论坛主题 https://forums.xamarin.com/discussion/159477/xamarin-forms-push-notification-is-not-receiving-to-ios-device#latest