Ccmmutty logo
Commutty IT
4 min read

Xamarin.iOSのFirebase Cloud MessagingでToken取得

https://cdn.magicode.io/media/notebox/ff64f0fd-2c88-4ca3-b60a-f0f9dd132efc.jpeg
1.Firebaseコンソールにプロジェクトを追加します。(バンドル識別子を入力してください。) 追加する際、「GoogleService-Info.plist」のダウンロードをダウンロードします。
2.「GoogleService-Info.plist」をiOSのプロジェクトに追加し、ビルドアクションを「BundleResource」に設定します。
3.Nugetパッケージインストールより、Xamarin.Firebase.iOS.CloudMessagingをインストールします。
4.AppDelegateのFinishedLunchingに Firebase.Core.App.Configure(); を追記します。
5.AppDelegateに任意のクラスを追加し、以下のコードを追加します。
    private void InitFCM()
    {
        // Register your app for remote notifications.
        if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {

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

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

    }
6.作成した関数をFinishedLunchingで呼び出します。(Firebase.Core.App.Configure();以下に追加してください。)
7.AppDelegateに以下の関数を追加してください。
    [Export("messaging:didReceiveRegistrationToken:")]
    public void DidReceiveRegistrationToken(Messaging messaging, string fcmToken)
    {
        Console.WriteLine($"Firebase registration token: {fcmToken}");


        Console.WriteLine($"Apns token is {Messaging.SharedInstance.ApnsToken}");

        // TODO: If necessary send token to application server.
        // Note: This callback is fired at each app startup and whenever a new token is generated.
        m_AddTopic.Invoke(fcmToken);
    }
name spaceは以下の通りです。
using System;
using Firebase.CloudMessaging;
using Foundation;
using UIKit;
using UserNotifications;
以上の実装を行うことで、実行後に出力タブにFCMトークンが出力されます。
ご覧いただきありがとうございました。

Discussion

コメントにはログインが必要です。