适用于iOS的Xamarin Firebase会出现fcm 501错误

时间:2017-12-11 18:41:15

标签: ios firebase xamarin firebase-cloud-messaging

我已经在这几天苦苦挣扎,并且已经找到了很多关于这个主题的帖子,但似乎没有什么能解决我的问题。我有一种感觉,这可能很简单,因为我已经尝试了几次减少项目并总是得到同样的失败。我可以在Android中收到很好的Firebase消息,但iOS一直让我失望。

我正在使用iOS 10手机作为测试。调试代码总是返回一个令牌,但在连接时,出现错误'无法完成操作。 (com.google.fcm错误501.)'被返回。我附上了一些示例代码 - 这已经挫败了

    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate, 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 ();
        LoadApplication (new FirebaseTest.App (""));

        RegisterForNotificationFCM();
        return base.FinishedLaunching (app, options);
    }
    void RegisterForNotificationFCM()
    {
        // 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.Delegate = 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();

        Firebase.Analytics.Loader loader1 = new Firebase.Analytics.Loader();
        Firebase.InstanceID.Loader loader2 = new Firebase.InstanceID.Loader();

        //Firebase.Core.App.Configure();

        Firebase.InstanceID.InstanceId.Notifications.ObserveTokenRefresh((sender, e) =>
        {
            var newToken = Firebase.InstanceID.InstanceId.SharedInstance.Token;
            System.Diagnostics.Debug.WriteLine(newToken);

            connectFCM();
        });
    }
    public override void DidEnterBackground(UIApplication uiApplication)
    {
        Messaging.SharedInstance.ShouldEstablishDirectChannel = false;
    }

    public override void OnActivated(UIApplication uiApplication)
    {
        base.OnActivated(uiApplication);
    }

    public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
    {
        Messaging.SharedInstance.ApnsToken = deviceToken;
        connectFCM();
        //Firebase.InstanceID.InstanceId.SharedInstance.SetApnsToken(deviceToken, Firebase.InstanceID.ApnsTokenType.Prod);
    }

    public void DidRefreshRegistrationToken(Messaging msg, string str)
    {
    }

    //Fire when background received notification is clicked
    public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
    {
        //Messaging.SharedInstance.AppDidReceiveMessage(userInfo);
        System.Diagnostics.Debug.WriteLine(userInfo);

        // Generate custom event
        NSString[] keys = { new NSString("Event_type") };
        NSObject[] values = { new NSString("Recieve_Notification") };
        var parameters = NSDictionary<NSString, NSObject>.FromObjectsAndKeys(keys, values, keys.Length);

        // Send custom event
        Firebase.Analytics.Analytics.LogEvent("CustomEvent", parameters);

        if (application.ApplicationState == UIApplicationState.Active)
        {
            System.Diagnostics.Debug.WriteLine(userInfo);
            var aps_d = userInfo["aps"] as NSDictionary;
            var alert_d = aps_d["alert"] as NSDictionary;
            var body = alert_d["body"] as NSString;
            var title = alert_d["title"] as NSString;
            //debugAlert(title, body);
        }
    }

    [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
    public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
    {
        // Do your magic to handle the notification data
        System.Console.WriteLine(notification.Request.Content.UserInfo);
    }

    // Receive data message on iOS 10 devices.
    public void ApplicationReceivedRemoteMessage(RemoteMessage remoteMessage)
    {
        Console.WriteLine(remoteMessage.AppData);
    }

    private void connectFCM()
    {
        //Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
        //Messaging.SharedInstance.Subscribe("/topics/topic");
        Messaging.SharedInstance.Connect((error) =>
        {
            if (error == null)
            {
                Messaging.SharedInstance.Subscribe("/topics/topic");
            }
            System.Diagnostics.Debug.WriteLine(error != null ? "error occured" : "connect success");
        });
    }

这些功能已从同一主题的许多其他帖子中删除,就像您越来越绝望时所发生的那样。我认为firebase控制台已经设置好了。我已将iOS作为应用程序添加到正常工作的Android上,并添加了在Mac上创建的身份验证密钥。 (令人惊讶的是,即使没有这个iOS应用程序作为firebase项目的一部分,我仍然得到一个令牌 - 不是我所期望的)已经为这个应用程序创建了一个证书,并且已经重新创建了配置文件并删除了旧的。

我不确定还有什么要补充的 - 有人请我摆脱我的痛苦......

1 个答案:

答案 0 :(得分:0)

到最后到达那里。其他人检查的事情 - 将App.Configure()移动到connectFCM

    private void connectFCM()
    {
        Firebase.Core.App.Configure();

        Messaging.SharedInstance.ShouldEstablishDirectChannel = true;
    }

并将以下内容添加到info.plist

<key>NSExceptionDomains</key>
<dict>
    <key>firebaseio.com</key>
    <dict>
        <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
        <true/>
        <key>NSIncludesSubdomains</key>
        <true/>
    </dict>
</dict>
<key>UIBackgroundModes</key>
<array>
    <string>remote-notification</string>
</array>