チュートリアル: バックエンド サービス経由で Azure Notification Hubs を使用して React Native アプリにプッシュ通知を送信する

サンプル ダウンロード サンプル をダウンロードする

  • Xamarin.Forms の
  • Flutter
  • React ネイティブ の

このチュートリアルでは、Azure Notification Hubs を使用して、Android と iOSを対象とする React Native アプリケーション プッシュ通知 します。

ASP.NET Core Web API バックエンドは、最新かつ最適な インストール アプローチを使用して、クライアントの デバイス登録 を処理するために使用されます。 また、サービスはクロスプラットフォーム方式でプッシュ通知を送信します。

これらの操作は、バックエンド操作のNotification Hubs SDK を使用して処理されます。 全体的なアプローチの詳細については、アプリ バックエンドからの登録 ドキュメントを参照してください。

このチュートリアルでは、次の手順を実行します。

前提 条件

これに従うには、次のものが必要です。

  • Azure サブスクリプション リソースを作成および管理できます。
  • Visual Studio for Mac がインストールされている Mac (または Visual Studio 2019 実行されている PC、.NET ワークロードを使用した Mobile Development)。
  • Android (物理デバイスまたはエミュレーター デバイス) または iOS (物理デバイスのみ) でアプリを実行する機能。

Android の場合は、次が必要です。

  • 開発者が物理デバイスのロックを解除するか、エミュレーター (Google Play Services がインストールされた状態で API 26 以降を実行)

iOS の場合は、次が必要です。

  • アクティブな Apple Developer Account
  • (iOS 13.0 以降を実行している)開発者アカウントに登録 物理 iOS デバイス
  • .p12開発証明書 キーチェーンにインストール、物理デバイスでアプリを 実行できます。

手記

iOS シミュレーターはリモート通知をサポートしていないため、iOS でこのサンプルを探索するときは物理デバイスが必要です。 ただし、このチュートリアルを完了するために、AndroidiOS の両方でアプリを実行する必要はありません。

この最初の原則の例の手順は、以前の経験なしで実行できます。 ただし、次の点を理解することでメリットが得られるでしょう。

提供される手順は、Visual Studio for Mac と Visual Studio Code 用ですが、Visual Studio 2019を使用して作業を進め。

プッシュ通知サービスと Azure Notification Hub を設定する

このセクションでは、Firebase Cloud Messaging (FCM)Apple Push Notification Services (APNS)を設定します。 次に、これらのサービスを操作するための通知ハブを作成して構成します。

Firebase プロジェクトを作成し、Android 用 Firebase Cloud Messaging を有効にする

  1. Firebase コンソールにサインインします。 プロジェクト名として PushDemo 入力新しい Firebase プロジェクトを作成します。

    手記

    一意の名前が自動的に生成されます。 既定では、これは、指定した名前の小文字のバリアントと、ダッシュで区切られた生成された番号で構成されます。 グローバルに一意である場合は、これを変更できます。

  2. プロジェクトを作成したら、[Firebase を Android アプリに追加] を選択します。

    Firebase を Android アプリの に追加する

  3. [Add Firebase to your Android app]\(Firebase を Android アプリに追加する\) ページで、次の手順を実行します。

    1. Android パッケージ名に、パッケージの名前を入力します。 例: com.<organization_identifier>.<package_name>.

      パッケージ名の を指定する

    2. [アプリ登録] を選択します。

    3. [google-services.jsonダウンロード] を選択します。 次に、後で使用するためにファイルをローカル フォルダーに保存し、[次 ] を選択します。

      ダウンロード google-services.json

    4. [次選択します。

    5. [続行 コンソール を選択する

      手記

      インストールの確認 チェックが のため、[コンソール に進む] ボタンが有効になっていない場合は、[この手順スキップ 選択します。

  4. Firebase コンソールで、プロジェクトの歯車を選択します。 次に、[プロジェクト設定]選択します。

    プロジェクト設定の選択

    手記

    google-services.json ファイルをダウンロードしていない場合は、このページでダウンロードできます。

  5. 上部にある [クラウド メッセージング] タブに切り替えます。 後で使用するために、サーバー キー をコピーして保存します。 この値を使用して、通知ハブを構成します。

    サーバー キーの をコピーする

プッシュ通知用に iOS アプリを登録する

iOS アプリにプッシュ通知を送信するには、Apple にアプリケーションを登録し、プッシュ通知にも登録します。

  1. まだアプリを登録していない場合は、Apple デベロッパー センターの iOS プロビジョニング ポータル を参照します。 Apple ID を使用してポータルにサインインし、証明書、識別子、プロファイル &に移動し、[識別子]を選択します。 + をクリックして新しいアプリを登録します。

    iOS プロビジョニング ポータルのアプリ ID ページ

  2. [新しい識別子の登録] 画面で、[アプリ ID] ラジオ ボタンを選択します。 次に、[続行]選択します。

    iOS プロビジョニング ポータル 新しい ID ページを登録

  3. 新しいアプリの次の 3 つの値を更新し、[続行]選択します。

    • 説明: アプリのわかりやすい名前を入力します。

    • バンドル ID: フォームのバンドル ID 入力します。<organization_identifier>。アプリ配布ガイドのに記載されている<product_name>。 次のスクリーンショットでは、mobcat 値が組織識別子として使用され、PushDemo 値が製品名として使用されています。

      iOS プロビジョニング ポータル アプリ ID の登録ページ

    • プッシュ通知の: [機能] セクションの [プッシュ通知] オプションをオンにします。

      フォームで新しいアプリ ID を登録する

      このアクションにより、アプリ ID が生成され、情報の確認が要求されます。 [続行]選択し、[ 登録] を選択して新しいアプリ ID を確認します。

      新しいアプリ ID を確認する

      の登録 選択すると、新しいアプリ ID が [証明書、識別子 & プロファイル] ページに行項目として表示されます。

  4. [証明書] の [識別子 & プロファイル] ページの [識別子]で、作成したアプリ ID の行項目を見つけます。 次に、その行を選択して、[アプリ ID 構成の編集] 画面 表示します。

Notification Hubs の証明書の作成

Apple Push Notification Services (APNS) で通知ハブを操作できるようにするために証明書が必要であり、次の 2 つの方法のいずれかで提供できます。

  1. Notification Hub に直接アップロードできる p12 プッシュ証明書の作成 (元のアプローチ)

  2. トークン ベースの認証 に使用できる p8 証明書の作成 (新しい推奨されるアプローチ)

新しいアプローチには、APNSの トークン ベース (HTTP/2) 認証に関するページに記載されているように、多くの利点があります。 必要な手順は少なくなりますが、特定のシナリオでも必須です。 ただし、どちらの方法でもこのチュートリアルの目的で機能するため、両方の方法の手順が提供されています。

オプション 1: Notification Hub に直接アップロードできる p12 プッシュ証明書を作成する
  1. Mac で、キーチェーン アクセス ツールを実行します。 Utilities フォルダーまたはスタート パッドの Other フォルダーから開くことができます。

  2. キーチェーン アクセス選択し、証明書アシスタント展開して、証明機関から証明書 要求を選択します。

    キーチェーン アクセスを使用して新しい証明書 を要求する

    手記

    既定では、キーチェーン アクセスはリスト内の最初の項目を選択します。 これは、証明書 カテゴリに属していて、Apple Worldwide Developer Relations 証明機関 がリストの最初の項目でない場合に問題になる可能性があります。 CSR (証明書署名要求) を生成する前に、キー以外の項目があることを確認するか、Apple Worldwide Developer Relations 証明機関 キー が選択されていることを確認します。

  3. ユーザーの電子メール アドレスを選択し、共通名の の値を入力し、[ディスクに保存] 指定していることを確認し、[続行]選択します。 CA 電子メール アドレス は不要であるため、空白のままにします。

    予想される証明書情報の

  4. [名前を付けて保存]に 証明書署名要求 (CSR) ファイルの名前 入力し、[場所] で場所 選択し、[保存] 選択します。

    証明書のファイル名を選択

    このアクションにより、選択した場所に CSR ファイル が保存されます。 既定の場所はデスクトップです。 ファイルに対して選択した場所を覚えておいてください。

  5. iOS プロビジョニング ポータル証明書、識別子 & プロファイル ページに戻り、チェックされた [プッシュ通知] オプションまで下にスクロールし、[ の構成] 選択して証明書を作成します。

    [アプリ ID の編集] ページの

  6. [Apple Push Notification service TLS/SSL Certificates] ウィンドウが表示されます。 [開発 TLS/SSL 証明書] セクションの下にある [証明書 の作成 ] ボタンを選択します。

    [アプリ ID の証明書の作成] ボタンの

    新しい証明書 の作成画面が表示されます。

    手記

    このチュートリアルでは、開発証明書を使用します。 運用環境の証明書を登録する場合も同じプロセスが使用されます。 通知を送信するときは、必ず同じ種類の証明書を使用してください。

  7. [ファイル選択] を選択し、CSR ファイルを保存した場所を参照し、証明書名をダブルクリックして読み込みます。 次に、[続行]選択します。

  8. ポータルで証明書を作成した後、ダウンロード ボタンを選択します。 証明書を保存し、保存先の場所を覚えておいてください。

    生成された証明書のダウンロード ページ

    証明書がダウンロードされ、ダウンロード フォルダーにコンピューターに保存されます。

    ダウンロード フォルダー内の証明書ファイルを検索

    手記

    既定では、ダウンロードした開発証明書には aps_development.cerという名前が付けられます。

  9. ダウンロードしたプッシュ証明書の aps_development.cerをダブルクリックします。 この操作により、次の図に示すように、キーチェーンに新しい証明書がインストールされます。

    新しい証明書 を示すキーチェーン アクセス証明書の一覧を する

    手記

    証明書内の名前は異なる場合がありますが、名前の前に Apple Development iOS Push Services が付き、適切なバンドル識別子が関連付けられます。

  10. キーチェーン アクセスで、コントロール + 証明書 カテゴリで作成した新しいプッシュ証明書の をクリックします。 [エクスポート選択し、ファイルに名前を付け、p12 形式を選択して、[保存] 選択します。

    p12 形式で証明書をエクスポート

    証明書をパスワードで保護することもできますが、パスワードは省略可能です。 パスワードの作成 バイパスする場合は、[OK] をクリックします。 エクスポートした p12 証明書のファイル名と場所を書き留めます。 これらは、APN での認証を有効にするために使用されます。

    手記

    p12 ファイルの名前と場所は、このチュートリアルで説明されているものとは異なる場合があります。

オプション 2: トークン ベースの認証に使用できる p8 証明書を作成する
  1. 次の詳細を書き留めます。

    • アプリ ID プレフィックス (チーム ID)
    • バンドル ID
  2. 証明書、識別子 & プロファイルに戻り、[キーの] をクリックします。

    手記

    APNS用に構成されたキーが既にある場合は、作成直後にダウンロードした p8 証明書を再利用できます。 その場合は、5までの 3 手順を無視できます。

  3. [+] ボタン (または [キーの作成] ボタン) をクリックして、新しいキーを作成します。

  4. 適切な キー名 値を指定し、Apple Push Notifications サービス (APNS) オプションをオンにして、[続行] をクリックし、次の画面で [登録] をクリックします。

  5. [ ダウンロード] をクリックし、p8 ファイル (プレフィックスは AuthKey_) をセキュリティで保護されたローカル ディレクトリに移動し、[完了] クリック

    手記

    p8 ファイルは安全な場所に保管してください (バックアップを保存してください)。 キーをダウンロードした後は、サーバーのコピーが削除されるため、再ダウンロードできません。

  6. キーで、作成したキー (または代わりに使用することを選択した場合は既存のキー) をクリックします。

  7. キー ID 値を書き留めます。

  8. Visual Studio Codeなど、任意の適切なアプリケーションで p8 証明書を開きます。 キーの値 (----- BEGIN 秘密キー---------- END 秘密キー-----) を書き留めます。

    -----秘密キーを使用します-----
    <key_value>
    秘密キーを-----します-----

    手記

    これは、後で Notification Hubを構成するために使用される トークン値 です。

これらの手順の最後には、「APNS 情報を使用して通知ハブを構成する 後で使用するための次の情報が必要です。

  • チーム ID (手順 1 を参照)
  • バンドル ID (手順 1 を参照)
  • キー ID (手順 7 を参照)
  • トークン値 (手順 8 で取得した p8 キー値)

アプリのプロビジョニング プロファイルを作成する

  1. iOS プロビジョニング ポータルに戻り、[証明書 ]、[識別子]、[プロファイル] &の順に選択し、左側のメニューから [プロファイル] を選択し、+ を選択して新しいプロファイルを作成します。 [新しいプロビジョニング プロファイルの登録] 画面が表示されます。

  2. プロビジョニング プロファイル [開発] の下にある [iOS アプリ開発 を選択し、[続行]選択します。

    プロビジョニング プロファイルの一覧

  3. 次に、[アプリ ID] ドロップダウン リストから作成したアプリ ID を選択し、[続行]選択します。

    アプリ ID を選択する

  4. [証明書の選択] ウィンドウで、コード署名に使用する開発証明書を選択し、[続行]選択します。

    手記

    この証明書は、前の手順で作成したプッシュ証明書ではありません。 これは開発証明書です。 存在しない場合は、このチュートリアルの 前提条件 であるため、作成する必要があります。 開発者証明書は、Apple Developer Portal、xcode、または Visual Studio使用して作成できます。

  5. 証明書、識別子 & プロファイル ページに戻り、左側のメニューから プロファイル を選択し、+ を選択して新しいプロファイルを作成します。 [新しいプロビジョニング プロファイルの登録] 画面が表示されます。

  6. 証明書の選択 ウィンドウで、作成した開発証明書を選択します。 次に、[続行]選択します。

  7. 次に、テストに使用するデバイスを選択し、[続行]選択します。

  8. 最後に、[プロビジョニング プロファイル名]でプロファイルの名前 選択し、[の生成] 選択します。

    プロビジョニング プロファイル名を選択

  9. 新しいプロビジョニング プロファイルが作成されたら、[のダウンロード] 選択します。 保存先の場所を覚えておいてください。

  10. プロビジョニング プロファイルの場所を参照し、それをダブルクリックして開発用コンピューターにインストールします。

通知ハブを作成する

このセクションでは、通知ハブを作成し、APNSを使用して認証を構成します。 p12 プッシュ証明書またはトークン ベースの認証を使用できます。 既に作成した通知ハブを使用する場合は、手順 5 に進むことができます。

  1. Azureにサインインします。

  2. [リソース作成] をクリックし、Notification Hub検索して選択し、[の作成] クリックします。

  3. 次のフィールドを更新し、の作成 クリックします。

    基本的な詳細 を する

    サブスクリプション: ドロップダウン リストからターゲット サブスクリプション を選択します
    リソース グループ: 新しい リソース グループ を作成する (または既存のものを選択する)

    名前空間の詳細 を する

    Notification Hub 名前空間:Notification Hub 名前空間のグローバルに一意の名前を入力します

    手記

    このフィールドに 新しい の作成オプションが選択されていることを確認します。

    通知ハブの詳細 を する

    通知ハブ:Notification Hub の名前を入力します
    場所: ドロップダウン リストから適切な場所を選択します
    価格レベル: 既定の Free オプションを保持する

    手記

    Free レベルのハブの最大数に達していない限り。

  4. Notification Hub がプロビジョニングされたら、そのリソースに移動します。

  5. 新しい Notification Hubに移動します。

  6. 一覧から アクセス ポリシー を選択します ([manage] の下 )。

  7. ポリシー名の 値と、対応する 接続文字列 値を書き留めます。

APNS 情報を使用して Notification Hub を構成する

Notification Servicesで、Apple 選択し、「Notification Hubs の証明書の作成 」セクションで前に選択した方法に基づいて適切な手順に従います。

手記

ストアからアプリを購入したユーザーにプッシュ通知を送信する場合にのみ、アプリケーション モードの運用 を使用します。

オプション 1: .p12 プッシュ証明書の使用

  1. [証明書選択します。

  2. ファイル アイコンを選択します。

  3. 先ほどエクスポートした .p12 ファイルを選択し、[を開く] 選択します。

  4. 必要に応じて、正しいパスワードを指定します。

  5. サンドボックス モード 選択します。

  6. [保存]を選択します。

オプション 2: トークン ベースの認証を使用する

  1. [トークン選択します。

  2. 前に取得した次の値を入力します。

    • キー ID
    • バンドル ID
    • チーム ID
    • トークンの
  3. [サンドボックス選択します。

  4. [保存]を選択します。

FCM 情報を使用して通知ハブを構成する

  1. 左側 メニューの [設定] セクションで Google (GCM/FCM) を選択します。
  2. Google Firebase Consoleから、サーバー キー 入力します。
  3. ツール バー [保存] を選択します。

ASP.NET Core Web API バックエンド アプリケーションを作成する

このセクションでは、デバイス登録 と React Native モバイル アプリへの通知の送信を処理する ASP.NET Core Web API バックエンドを作成します。

Web プロジェクトを作成する

  1. Visual Studioで、[ファイル][新しいソリューション]選択します。

  2. [.NET CoreAppASP.NET CoreAPINext] を選択します。

  3. [新しい ASP.NET Core Web API の構成] ダイアログで、.NET Core 3.1のターゲット フレームワーク 選択します。

  4. プロジェクト名 に「PushDemoApi 入力し、[作成]選択します。

  5. デバッグを開始 (コマンド + Enter) して、テンプレート 化されたアプリをテストします。

    手記

    テンプレートアプリは、launchUrlとして WeatherForecastController を使用するように構成されています。 これは、プロパティ>launchSettings.jsonで設定されます。

    無効な開発証明書が見つかりました メッセージが表示された場合:

    1. [はい] をクリックして、"dotnet dev-certs https" ツールを実行してこれを修正することに同意します。 "dotnet dev-certs https" ツールでは、証明書のパスワードとキーチェーンのパスワードの入力を求められます。

    2. インストールを し、新しい証明書を信頼するように求められたら、[はい] をクリックし、キーチェーンのパスワードを入力します。

  6. Controllers フォルダーを展開し、WeatherForecastController.csを削除します。

  7. WeatherForecast.csを削除します。

  8. Secret Manager ツールを使用してローカル構成値を設定します。 シークレットをソリューションから切り離すことで、最終的にソース管理が行われることはありません。 ターミナル 開き、プロジェクト ファイルのディレクトリに移動し、次のコマンドを実行します。

    dotnet user-secrets init
    dotnet user-secrets set "NotificationHub:Name" <value>
    dotnet user-secrets set "NotificationHub:ConnectionString" <value>
    

    プレースホルダーの値を、独自の通知ハブ名と接続文字列の値に置き換えます。 通知ハブ の作成セクション でメモしておきます。 それ以外の場合は、Azureで検索できます。

    NotificationHub:Name:
    の概要の上部にある Essentials 概要の を参照してください。

    NotificationHub:ConnectionString:
    アクセス ポリシー の DefaultFullSharedAccessSignature の を参照してください

    手記

    運用環境のシナリオでは、Azure KeyVault を して接続文字列を安全に格納するオプションを確認できます。 わかりやすくするために、シークレットは Azure App Service アプリケーション設定 に追加されます。

API キーを使用してクライアントを認証する (省略可能)

API キーはトークンほど安全ではありませんが、このチュートリアルでは十分です。 API キーは、ASP.NET ミドルウェアを使用して簡単に構成できます。

  1. API キー をローカル構成値に追加します。

    dotnet user-secrets set "Authentication:ApiKey" <value>
    

    手記

    プレースホルダーの値を独自の値に置き換え、メモする必要があります。

  2. コントロールPushDemoApi プロジェクトの [] をクリックし、[ の追加] メニューから [新しいフォルダー を選択し、フォルダー名として 認証 を使用して を追加 ] をクリックします。

  3. コントロール認証 フォルダーの [] をクリックし、[追加] メニューの [新しいファイル]< 選択します。

  4. [全般][空のクラス]選択し、[名]ApiKeyAuthOptions.cs を入力し、[新規] クリック、次の実装を追加します。

    using Microsoft.AspNetCore.Authentication;
    
    namespace PushDemoApi.Authentication
    {
        public class ApiKeyAuthOptions : AuthenticationSchemeOptions
        {
            public const string DefaultScheme = "ApiKey";
            public string Scheme => DefaultScheme;
            public string ApiKey { get; set; }
        }
    }
    
  5. ApiKeyAuthHandler.csという名前 Authentication フォルダーに空のクラス を追加し、次の実装を追加します。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Claims;
    using System.Text.Encodings.Web;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    
    namespace PushDemoApi.Authentication
    {
        public class ApiKeyAuthHandler : AuthenticationHandler<ApiKeyAuthOptions>
        {
            const string ApiKeyIdentifier = "apikey";
    
            public ApiKeyAuthHandler(
                IOptionsMonitor<ApiKeyAuthOptions> options,
                ILoggerFactory logger,
                UrlEncoder encoder,
                ISystemClock clock)
                : base(options, logger, encoder, clock) {}
    
            protected override Task<AuthenticateResult> HandleAuthenticateAsync()
            {
                string key = string.Empty;
    
                if (Request.Headers[ApiKeyIdentifier].Any())
                {
                    key = Request.Headers[ApiKeyIdentifier].FirstOrDefault();
                }
                else if (Request.Query.ContainsKey(ApiKeyIdentifier))
                {
                    if (Request.Query.TryGetValue(ApiKeyIdentifier, out var queryKey))
                        key = queryKey;
                }
    
                if (string.IsNullOrWhiteSpace(key))
                    return Task.FromResult(AuthenticateResult.Fail("No api key provided"));
    
                if (!string.Equals(key, Options.ApiKey, StringComparison.Ordinal))
                    return Task.FromResult(AuthenticateResult.Fail("Invalid api key."));
    
                var identities = new List<ClaimsIdentity> {
                    new ClaimsIdentity("ApiKeyIdentity")
                };
    
                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identities), Options.Scheme);
    
                return Task.FromResult(AuthenticateResult.Success(ticket));
            }
        }
    }
    

    手記

    認証ハンドラー は、スキームの動作 (この場合はカスタム API キー スキーム) を実装する型です。

  6. 別の Empty クラスApiKeyAuthenticationBuilderExtensions.csという名前の Authentication フォルダーに追加し、次の実装を追加します。

    using System;
    using Microsoft.AspNetCore.Authentication;
    
    namespace PushDemoApi.Authentication
    {
        public static class AuthenticationBuilderExtensions
        {
            public static AuthenticationBuilder AddApiKeyAuth(
                this AuthenticationBuilder builder,
                Action<ApiKeyAuthOptions> configureOptions)
            {
                return builder
                    .AddScheme<ApiKeyAuthOptions, ApiKeyAuthHandler>(
                        ApiKeyAuthOptions.DefaultScheme,
                        configureOptions);
            }
        }
    }
    

    手記

    この拡張メソッドは、ミドルウェア構成コードを簡略化 Startup.cs、より読みやすく、一般的に従いやすくします。

  7. Startup.csで、ConfigureServices メソッドを更新して、サービスの呼び出しの下で API キー認証を構成します。AddControllers メソッド。

    using PushDemoApi.Authentication;
    using PushDemoApi.Models;
    using PushDemoApi.Services;
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
    
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = ApiKeyAuthOptions.DefaultScheme;
            options.DefaultChallengeScheme = ApiKeyAuthOptions.DefaultScheme;
        }).AddApiKeyAuth(Configuration.GetSection("Authentication").Bind);
    }
    
  8. 引き続き Startup.csで、Configure メソッドを更新して、UseAuthentication を呼び出し、アプリの IApplicationBuilderで UseAuthorization 拡張メソッドを します。 これらのメソッドは、UseRouting 後、およびアプリの前 呼び出されていることを確認します。UseEndpoints.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseHttpsRedirection();
    
        app.UseRouting();
    
        app.UseAuthentication();
    
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
    

    手記

    UseAuthentication を呼び出すと、(ConfigureServicesから) 以前に登録された認証スキームを使用するミドルウェアが登録されます。 これは、認証されるユーザーに依存するミドルウェアの前に呼び出す必要があります。

依存関係の追加とサービスの構成

ASP.NET Core では、依存関係挿入 (DI) ソフトウェア設計パターンがサポートされています。これは、クラスとその依存関係の間で制御の反転 (IoC) を実現するための手法です。

バックエンド操作 に通知ハブと Notification Hubs SDK を使用することは、サービス内にカプセル化されます。 サービスは登録され、適切な抽象化によって利用できるようになります。

  1. Control + Dependencies フォルダーの [] をクリックし、[NuGet パッケージの管理]選択します。..

  2. Microsoft.Azure.NotificationHubs を検索し、チェックされていることを確認します。

  3. [パッケージ追加] をクリックし、ライセンス条項 同意するように求められたら[ に同意する] をクリックします。

  4. コントロールPushDemoApi プロジェクトの [] をクリックし、[ の追加] メニューから [新しいフォルダー 選択し、フォルダー名として [モデル] を使用して を追加 をクリックします。

  5. コントロールModels フォルダーの [] をクリックし、[ の追加] メニュー から [新しいファイル を選択します。

  6. [全般][空のクラス]選択し、[名]PushTemplates.cs を入力し、[新規 ] をクリック 次の実装を追加します。

    namespace PushDemoApi.Models
    {
        public class PushTemplates
        {
            public class Generic
            {
                public const string Android = "{ \"notification\": { \"title\" : \"PushDemo\", \"body\" : \"$(alertMessage)\"}, \"data\" : { \"action\" : \"$(alertAction)\" } }";
                public const string iOS = "{ \"aps\" : {\"alert\" : \"$(alertMessage)\"}, \"action\" : \"$(alertAction)\" }";
            }
    
            public class Silent
            {
                public const string Android = "{ \"data\" : {\"message\" : \"$(alertMessage)\", \"action\" : \"$(alertAction)\"} }";
                public const string iOS = "{ \"aps\" : {\"content-available\" : 1, \"apns-priority\": 5, \"sound\" : \"\", \"badge\" : 0}, \"message\" : \"$(alertMessage)\", \"action\" : \"$(alertAction)\" }";
            }
        }
    }
    

    手記

    このクラスには、このシナリオで必要な汎用通知とサイレント通知のトークン化された通知ペイロードが含まれています。 ペイロードは、サービスを介して既存のインストールを更新することなく実験できるように、インストール の外部で定義されます。 この方法でのインストールの変更の処理は、このチュートリアルでは範囲外です。 運用環境では、カスタム テンプレートすることを検討してください。

  7. 別の 空のクラスDeviceInstallation.csという名前の Models フォルダーに追加し、次の実装を追加します。

    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace PushDemoApi.Models
    {
        public class DeviceInstallation
        {
            [Required]
            public string InstallationId { get; set; }
    
            [Required]
            public string Platform { get; set; }
    
            [Required]
            public string PushChannel { get; set; }
    
            public IList<string> Tags { get; set; } = Array.Empty<string>();
        }
    }
    
  8. 別の 空のクラスNotificationRequest.csという名前の Models フォルダーに追加し、次の実装を追加します。

    using System;
    
    namespace PushDemoApi.Models
    {
        public class NotificationRequest
        {
            public string Text { get; set; }
            public string Action { get; set; }
            public string[] Tags { get; set; } = Array.Empty<string>();
            public bool Silent { get; set; }
        }
    }
    
  9. NotificationHubOptions.csという名前 Models フォルダーに空のクラス をもう 1 つ追加し、次の実装を追加します。

    using System.ComponentModel.DataAnnotations;
    
    namespace PushDemoApi.Models
    {
        public class NotificationHubOptions
        {
            [Required]
            public string Name { get; set; }
    
            [Required]
            public string ConnectionString { get; set; }
        }
    }
    
  10. Servicesと呼ばれる新しいフォルダーを PushDemoApi プロジェクトに追加します。

  11. 空のインターフェイスINotificationService.csという名前の Services フォルダーに追加し、次の実装を追加します。

    using System.Threading;
    using System.Threading.Tasks;
    using PushDemoApi.Models;
    
    namespace PushDemoApi.Services
    {
        public interface INotificationService
        {
            Task<bool> CreateOrUpdateInstallationAsync(DeviceInstallation deviceInstallation, CancellationToken token);
            Task<bool> DeleteInstallationByIdAsync(string installationId, CancellationToken token);
            Task<bool> RequestNotificationAsync(NotificationRequest notificationRequest, CancellationToken token);
        }
    }
    
  12. 空のクラスNotificationHubsService.csという名前の Services フォルダーに追加し、次のコードを追加して、INotificationService インターフェイスを実装します。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.NotificationHubs;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    using PushDemoApi.Models;
    
    namespace PushDemoApi.Services
    {
        public class NotificationHubService : INotificationService
        {
            readonly NotificationHubClient _hub;
            readonly Dictionary<string, NotificationPlatform> _installationPlatform;
            readonly ILogger<NotificationHubService> _logger;
    
            public NotificationHubService(IOptions<NotificationHubOptions> options, ILogger<NotificationHubService> logger)
            {
                _logger = logger;
                _hub = NotificationHubClient.CreateClientFromConnectionString(
                    options.Value.ConnectionString,
                    options.Value.Name);
    
                _installationPlatform = new Dictionary<string, NotificationPlatform>
                {
                    { nameof(NotificationPlatform.Apns).ToLower(), NotificationPlatform.Apns },
                    { nameof(NotificationPlatform.Fcm).ToLower(), NotificationPlatform.Fcm }
                };
            }
    
            public async Task<bool> CreateOrUpdateInstallationAsync(DeviceInstallation deviceInstallation, CancellationToken token)
            {
                if (string.IsNullOrWhiteSpace(deviceInstallation?.InstallationId) ||
                    string.IsNullOrWhiteSpace(deviceInstallation?.Platform) ||
                    string.IsNullOrWhiteSpace(deviceInstallation?.PushChannel))
                    return false;
    
                var installation = new Installation()
                {
                    InstallationId = deviceInstallation.InstallationId,
                    PushChannel = deviceInstallation.PushChannel,
                    Tags = deviceInstallation.Tags
                };
    
                if (_installationPlatform.TryGetValue(deviceInstallation.Platform, out var platform))
                    installation.Platform = platform;
                else
                    return false;
    
                try
                {
                    await _hub.CreateOrUpdateInstallationAsync(installation, token);
                }
                catch
                {
                    return false;
                }
    
                return true;
            }
    
            public async Task<bool> DeleteInstallationByIdAsync(string installationId, CancellationToken token)
            {
                if (string.IsNullOrWhiteSpace(installationId))
                    return false;
    
                try
                {
                    await _hub.DeleteInstallationAsync(installationId, token);
                }
                catch
                {
                    return false;
                }
    
                return true;
            }
    
            public async Task<bool> RequestNotificationAsync(NotificationRequest notificationRequest, CancellationToken token)
            {
                if ((notificationRequest.Silent &&
                    string.IsNullOrWhiteSpace(notificationRequest?.Action)) ||
                    (!notificationRequest.Silent &&
                    (string.IsNullOrWhiteSpace(notificationRequest?.Text)) ||
                    string.IsNullOrWhiteSpace(notificationRequest?.Action)))
                    return false;
    
                var androidPushTemplate = notificationRequest.Silent ?
                    PushTemplates.Silent.Android :
                    PushTemplates.Generic.Android;
    
                var iOSPushTemplate = notificationRequest.Silent ?
                    PushTemplates.Silent.iOS :
                    PushTemplates.Generic.iOS;
    
                var androidPayload = PrepareNotificationPayload(
                    androidPushTemplate,
                    notificationRequest.Text,
                    notificationRequest.Action);
    
                var iOSPayload = PrepareNotificationPayload(
                    iOSPushTemplate,
                    notificationRequest.Text,
                    notificationRequest.Action);
    
                try
                {
                    if (notificationRequest.Tags.Length == 0)
                    {
                        // This will broadcast to all users registered in the notification hub
                        await SendPlatformNotificationsAsync(androidPayload, iOSPayload, token);
                    }
                    else if (notificationRequest.Tags.Length <= 20)
                    {
                        await SendPlatformNotificationsAsync(androidPayload, iOSPayload, notificationRequest.Tags, token);
                    }
                    else
                    {
                        var notificationTasks = notificationRequest.Tags
                            .Select((value, index) => (value, index))
                            .GroupBy(g => g.index / 20, i => i.value)
                            .Select(tags => SendPlatformNotificationsAsync(androidPayload, iOSPayload, tags, token));
    
                        await Task.WhenAll(notificationTasks);
                    }
    
                    return true;
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Unexpected error sending notification");
                    return false;
                }
            }
    
            string PrepareNotificationPayload(string template, string text, string action) => template
                .Replace("$(alertMessage)", text, StringComparison.InvariantCulture)
                .Replace("$(alertAction)", action, StringComparison.InvariantCulture);
    
            Task SendPlatformNotificationsAsync(string androidPayload, string iOSPayload, CancellationToken token)
            {
                var sendTasks = new Task[]
                {
                    _hub.SendFcmNativeNotificationAsync(androidPayload, token),
                    _hub.SendAppleNativeNotificationAsync(iOSPayload, token)
                };
    
                return Task.WhenAll(sendTasks);
            }
    
            Task SendPlatformNotificationsAsync(string androidPayload, string iOSPayload, IEnumerable<string> tags, CancellationToken token)
            {
                var sendTasks = new Task[]
                {
                    _hub.SendFcmNativeNotificationAsync(androidPayload, tags, token),
                    _hub.SendAppleNativeNotificationAsync(iOSPayload, tags, token)
                };
    
                return Task.WhenAll(sendTasks);
            }
        }
    }
    

    手記

    SendTemplateNotificationAsync に提供されるタグ式は、20 個のタグに制限されています。 ほとんどの演算子では 6 に制限されていますが、この場合、式に含まれるのは OR (||) のみです。 要求に 20 個を超えるタグがある場合は、複数の要求に分割する必要があります。 詳細については、ルーティングとタグ式 ドキュメントを参照してください。

  13. Startup.csで、ConfigureServices メソッドを更新して、NotificationHubsService を INotificationServiceのシングルトン実装として追加 します。

    
    using PushDemoApi.Models;
    using PushDemoApi.Services;
    
    public void ConfigureServices(IServiceCollection services)
    {
        ...
    
        services.AddSingleton<INotificationService, NotificationHubService>();
    
        services.AddOptions<NotificationHubOptions>()
            .Configure(Configuration.GetSection("NotificationHub").Bind)
            .ValidateDataAnnotations();
    }
    

通知 API を作成する

  1. コントロール + Controllers フォルダーの [] をクリックし、[ 追加] メニューから [新しいファイル 選択します。..

  2. [コアWeb API コントローラー クラスASP.NET 選択し、に「NotificationsController 」と入力し、[新しい] をクリックします。

    手記

    Visual Studio 2019でフォローしている場合は、読み取り/書き込みアクションを含む API コントローラー テンプレートを選択します。

  3. ファイルの先頭に次の名前空間を追加します。

    using System.ComponentModel.DataAnnotations;
    using System.Net;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using PushDemoApi.Models;
    using PushDemoApi.Services;
    
  4. ControllerBase から派生し、ApiController 属性で修飾されるように、テンプレート化されたコントローラーを更新します。

    [ApiController]
    [Route("api/[controller]")]
    public class NotificationsController : ControllerBase
    {
        // Templated methods here
    }
    

    手記

    Controller 基本クラスはビューのサポートを提供しますが、この場合は必要ないため、代わりに ControllerBase 使用できます。 Visual Studio 2019でフォローしている場合は、この手順をスキップできます。

  5. API キー セクションを使用してクライアントを認証する を完了する場合は、NotificationsControllerAuthorize 属性で修飾する必要があります。

    [Authorize]
    
  6. INotificationService の登録済みインスタンスを引数として受け入れるようにコンストラクターを更新し、読み取り専用メンバーに割り当てます。

    readonly INotificationService _notificationService;
    
    public NotificationsController(INotificationService notificationService)
    {
        _notificationService = notificationService;
    }
    
  7. launchSettings.json (プロパティ フォルダー内) で、launchUrlweatherforecast から api/notifications に変更し、RegistrationsControllerRoute 属性で指定された URL に一致させます。

  8. デバッグを開始します (コマンド + Enter) して、アプリが新しい NotificationsController で動作していることを検証し、401 Unauthorized 状態を返します。

    手記

    Visual Studio がブラウザーでアプリを自動的に起動しない場合があります。 Postman 使用して、この時点から API をテストします。

  9. 新しい Postman タブで、要求を GET設定します。 applicationUrl プレースホルダーを、プロパティlaunchSettings.jsonにある https applicationUrl に置き換えて、次のアドレスを入力します。

    <applicationUrl>/api/notifications
    

    手記

    既定のプロファイルの場合、applicationUrl は 'https://localhost:5001' にする必要があります。 IIS (Windows Visual Studio 2019 の既定値) を使用している場合は、代わりに iisSettings 項目で指定された applicationUrl を使用する必要があります。 アドレスが正しくない場合は、404 応答を受け取ります。

  10. API キー セクションを使用してクライアントを認証する を完了する場合は、apikey 値を含めるように要求ヘッダーを構成してください。

    価値
    apikey <your_api_key>
  11. [送信] ボタンをクリックします。

    手記

    200 OK 状態を受け取り、一部の JSON コンテンツが表示されます。

    SSL 証明書検証 警告を受け取った場合は、[設定]で Postman 設定 SSL 証明書の要求検証をオフにすることができます。

  12. NotificationsController.cs のテンプレート化されたクラス メソッドを次のコードに置き換えます。

    [HttpPut]
    [Route("installations")]
    [ProducesResponseType((int)HttpStatusCode.OK)]
    [ProducesResponseType((int)HttpStatusCode.BadRequest)]
    [ProducesResponseType((int)HttpStatusCode.UnprocessableEntity)]
    public async Task<IActionResult> UpdateInstallation(
        [Required]DeviceInstallation deviceInstallation)
    {
        var success = await _notificationService
            .CreateOrUpdateInstallationAsync(deviceInstallation, HttpContext.RequestAborted);
    
        if (!success)
            return new UnprocessableEntityResult();
    
        return new OkResult();
    }
    
    [HttpDelete()]
    [Route("installations/{installationId}")]
    [ProducesResponseType((int)HttpStatusCode.OK)]
    [ProducesResponseType((int)HttpStatusCode.BadRequest)]
    [ProducesResponseType((int)HttpStatusCode.UnprocessableEntity)]
    public async Task<ActionResult> DeleteInstallation(
        [Required][FromRoute]string installationId)
    {
        var success = await _notificationService
            .DeleteInstallationByIdAsync(installationId, CancellationToken.None);
    
        if (!success)
            return new UnprocessableEntityResult();
    
        return new OkResult();
    }
    
    [HttpPost]
    [Route("requests")]
    [ProducesResponseType((int)HttpStatusCode.OK)]
    [ProducesResponseType((int)HttpStatusCode.BadRequest)]
    [ProducesResponseType((int)HttpStatusCode.UnprocessableEntity)]
    public async Task<IActionResult> RequestPush(
        [Required]NotificationRequest notificationRequest)
    {
        if ((notificationRequest.Silent &&
            string.IsNullOrWhiteSpace(notificationRequest?.Action)) ||
            (!notificationRequest.Silent &&
            string.IsNullOrWhiteSpace(notificationRequest?.Text)))
            return new BadRequestResult();
    
        var success = await _notificationService
            .RequestNotificationAsync(notificationRequest, HttpContext.RequestAborted);
    
        if (!success)
            return new UnprocessableEntityResult();
    
        return new OkResult();
    }
    

API アプリを作成する

これで、バックエンド サービスをホストするための API AppAzure App Service を作成します。

  1. Azure portalにサインインします。

  2. [リソース作成] をクリックし、API App検索して選択し、[の作成] クリックします。

  3. 次のフィールドを更新し、の作成 クリックします。

    アプリ名:
    API アプリ のグローバルに一意の名前を入力します

    サブスクリプション:
    通知ハブを作成したのと同じターゲット サブスクリプション を選択します。

    リソース グループ:
    通知ハブを作成したのと同じ リソース グループ を選択します。

    App Service プラン/場所:
    新しい App Service プラン を作成する

    手記

    既定のオプションから、SSL サポートを含むプランに変更します。 それ以外の場合は、モバイル アプリを操作するときに適切な手順を実行して、http 要求 ブロックされないようにする必要があります。

    Application Insights:
    推奨されるオプション (その名前を使用して新しいリソースが作成されます) をそのまま使用するか、既存のリソースを選択します。

  4. API アプリ がプロビジョニングされたら、そのリソースに移動します。

  5. の [概要]の上部にある Essentials の概要に、URL プロパティを書き留めます。 この URL は、このチュートリアルの後半で使用する バックエンド エンドポイントの です。

    手記

    この URL では、前に指定した API アプリ名が、https://<app_name>.azurewebsites.net形式で使用されます。

  6. 一覧から 構成 を選択します ([設定])。

  7. 以下の各設定で、[新しいアプリケーション設定 をクリックして 名の値のを入力し、[OK]クリックします。

    名前 価値
    Authentication:ApiKey <api_key_value>
    NotificationHub:Name <hub_name_value>
    NotificationHub:ConnectionString <hub_connection_string_value>

    手記

    これらは、ユーザー設定で以前に定義した設定と同じです。 これらをコピーできる必要があります。 Authentication:ApiKey 設定は、API キー セクションを使用してクライアントを認証する を完了することを選択した場合にのみ必要です。 運用環境のシナリオでは、Azure KeyVaultなどのオプションを確認できます。 これらは、この場合にわかりやすくするためにアプリケーション設定として追加されています。

  8. すべてのアプリケーション設定が追加されたら、保存をクリックし、[続行]します。

バックエンド サービスを発行する

次に、API アプリにアプリをデプロイして、すべてのデバイスからアクセスできるようにします。

手記

次の手順は、Visual Studio for Macに固有です。 Windows Visual Studio 2019 でフォローしている場合、発行フローは異なります。 WindowsAzure App Service への発行に関するページを参照してください。

  1. まだ行っていない場合は、構成を Debug から Release に変更します。

  2. ControlPushDemoApi プロジェクト クリックし、[発行] メニューから [Azure に発行] 選択

  3. 認証フローに従う必要がある場合は、それに従います。 前の手順で使用したアカウントを使用 、API アプリの セクションを作成します。

  4. 前に作成した Azure App Service API アプリ を発行ターゲットとして一覧から選択し、[発行] をクリックします。

ウィザードが完了すると、アプリが Azure に発行され、アプリが開きます。 まだ行っていない場合は、URL を書き留めておきます。 この URL は、このチュートリアルの後半で使用する バックエンド エンドポイントの です。

発行された API の検証

  1. Postman 新しいタブを開き、PUT 要求を設定し、以下のアドレスを入力します。 プレースホルダーを、前の バックエンド サービスの セクションでメモしたベース アドレスに置き換えます。

    https://<app_name>.azurewebsites.net/api/notifications/installations
    

    手記

    ベース アドレスは、https://<app_name>.azurewebsites.net/ の形式にする必要があります

  2. API キー セクションを使用してクライアントを認証する を完了する場合は、apikey 値を含めるように要求ヘッダーを構成してください。

    価値
    apikey <your_api_key>
  3. Bodyraw オプションを選択し、書式設定オプションの一覧から JSON 選択し、JSON コンテンツ プレースホルダーを含めます。

    {}
    
  4. [送信] をクリックします。

    手記

    サービスから 422 UnprocessableEntity 状態を受け取る必要があります。

  5. 手順 1 から 4 をもう一度実行しますが、今回は要求エンドポイントを指定して、400 Bad Request 応答を受け取ったかどうかを検証します。

    https://<app_name>.azurewebsites.net/api/notifications/requests
    

手記

クライアント モバイル アプリからプラットフォーム固有の情報が必要になるため、有効な要求データを使用して API をテストすることはできません。

クロスプラットフォームの React Native アプリケーションを作成する

このセクションでは、クロスプラットフォーム方式でプッシュ通知を実装する React Native モバイル アプリケーションを構築します。

これにより、作成したバックエンド サービスを介して通知ハブを登録および登録解除できます。

アクションが指定され、アプリがフォアグラウンドにある場合、アラートが表示されます。 それ以外の場合、通知は通知センターに表示されます。

手記

通常、登録 (および登録解除) アクションは、明示的なユーザー 登録/登録解除の入力なしで、アプリケーション ライフサイクルの適切な時点 (または最初の実行エクスペリエンスの一部として) 実行します。 ただし、この例では、この機能をより簡単に調査およびテストできるようにするために、明示的なユーザー入力が必要になります。

React Native ソリューションを作成する

  1. Terminalで、次のコマンドを使用して React Native を操作するために必要な環境ツールを更新します。

    # install node
    brew install node
    # or update
    brew update node
    # install watchman
    brew install watchman
    # or update
    brew upgrade watchman
    # install cocoapods
    sudo gem install cocoapods
    
  2. Terminalで、CLI をアンインストール React Native インストールされている場合は、次のコマンドを実行します。 npx を使用して、利用可能な最新の React Native CLI バージョンに自動的にアクセスします。

    npm uninstall -g react-native-cli
    

    手記

    React Native には、コマンド ライン インターフェイスが組み込まれています。 CLI の特定のバージョンをグローバルにインストールして管理するのではなく、Node.jsに付属する npxを使用して、実行時に現在のバージョンにアクセスすることをお勧めします。 npx react-native <command>では、CLI の現在の安定したバージョンがダウンロードされ、コマンドの実行時に実行されます。

  3. 新しいアプリケーションを作成するプロジェクト フォルダーに移動します。 --template パラメーターを指定して、Typescript ベースのテンプレートを使用します。

    # init new project with npx
    npx react-native init PushDemo --template react-native-template-typescript
    
  4. JavaScript バンドルをビルドし、コードの更新を監視してバンドルをリアルタイムで更新するメトロ サーバーを実行します。

    cd PushDemo
    npx react-native start
    
  5. iOS アプリを実行してセットアップを確認します。 次のコマンドを実行する前に、iOS シミュレーターを起動したか、iOS デバイスを接続していることを確認してください。

    npx react-native run-ios
    
  6. Android アプリを実行してセットアップを確認します。 React Native メトロ サーバーにアクセスできるように Android エミュレーターまたはデバイスを構成するには、追加の手順がいくつか必要です。 次のコマンドは、Android 用の初期 JavaScript バンドルを生成し、それを assets フォルダーに格納します。

    # create assets folder for the bundle
    mkdir android/app/scr/main/assets
    # build the bundle
    npx react-native bundle --platform android --dev true --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
    # enable ability for sim to access the localhost
    adb reverse tcp:8081 tcp:8081
    

    このスクリプトは、アプリの初期バージョンで事前にデプロイされます。 デプロイが完了したら、サーバーの IP アドレスを指定して、エミュレーターまたはデバイスがメトロ サーバーにアクセスするように構成します。 次のコマンドを実行して、Android アプリケーションをビルドして実行します。

    npx react-native run-android
    

    アプリで、CMD+M (エミュレーター) を押すか、デバイスをシェイクして開発者設定を設定し、Settings>Change Bundle Locationに移動し、既定のポート (<metro-server-ip-address>:8081) でメトロ サーバーの IP アドレスを指定します。

  7. App.tsx ファイルで、ページ レイアウトに変更を適用して保存し、変更が iOS アプリと Android アプリの両方に自動的に反映されるようにします。

    手記

    詳細な開発環境のセットアップ ガイドは、の公式ドキュメント で入手できます

必要なパッケージをインストールする

このサンプルを機能させるには、次の 3 つのパッケージが必要です。

  1. React ネイティブ プッシュ通知の iOS - Project GitHub

    このパッケージは、PushNotificationIOS が React Native のコアから分割されたときに作成されました。 このパッケージは、iOS 用のプッシュ通知をネイティブに実装し、それにアクセスするための React Native インターフェイスを提供します。 次のコマンドを実行してパッケージをインストールします。

    yarn add @react-native-community/push-notification-ios
    
  2. React ネイティブ プッシュ通知のクロスプラットフォーム の

    このパッケージは、クロスプラットフォームの方法で iOS および Android にローカルおよびリモート通知を実装します。 次のコマンドを実行してパッケージをインストールします。

    yarn add react-native-push-notification
    
  3. デバイス情報パッケージ パッケージは、実行時にデバイスに関する情報を提供します。 これを使用して、プッシュ通知の登録に使用されるデバイス識別子を定義します。 次のコマンドを実行してパッケージをインストールします。

    yarn add react-native-device-info
    

クロスプラットフォーム コンポーネントを実装する

  1. DemoNotificationHandlerを作成して実装します。

    import PushNotification from 'react-native-push-notification';
    
    class DemoNotificationHandler {
      private _onRegister: any;
      private _onNotification: any;
    
      onNotification(notification: any) {
        console.log('NotificationHandler:', notification);
    
        if (typeof this._onNotification === 'function') {
          this._onNotification(notification);
        }
      }
    
      onRegister(token: any) {
        console.log('NotificationHandler:', token);
    
        if (typeof this._onRegister === 'function') {
          this._onRegister(token);
        }
      }
    
      attachTokenReceived(handler: any) {
        this._onRegister = handler;
      }
    
      attachNotificationReceived(handler: any) {
        this._onNotification = handler;
      }
    }
    
    const handler = new DemoNotificationHandler();
    
    PushNotification.configure({
      onRegister: handler.onRegister.bind(handler),
      onNotification: handler.onNotification.bind(handler),
      permissions: {
        alert: true,
        badge: true,
        sound: true,
      },
      popInitialNotification: true,
      requestPermissions: true,
    });
    
    export default handler;
    
  2. DemoNotificationServiceを作成して実装します。

    import PushNotification from 'react-native-push-notification';
    import DemoNotificationHandler from './DemoNotificationHandler';
    
    export default class DemoNotificationService {
      constructor(onTokenReceived: any, onNotificationReceived: any) {
        DemoNotificationHandler.attachTokenReceived(onTokenReceived);
        DemoNotificationHandler.attachNotificationReceived(onNotificationReceived);
        PushNotification.getApplicationIconBadgeNumber(function(number: number) {
          if(number > 0) {
            PushNotification.setApplicationIconBadgeNumber(0);
          }
        });
      }
    
      checkPermissions(cbk: any) {
        return PushNotification.checkPermissions(cbk);
      }
    
      requestPermissions() {
        return PushNotification.requestPermissions();
      }
    
      cancelNotifications() {
        PushNotification.cancelLocalNotifications();
      }
    
      cancelAll() {
        PushNotification.cancelAllLocalNotifications();
      }
    
      abandonPermissions() {
        PushNotification.abandonPermissions();
      }
    }
    
  3. DemoNotificationRegistrationServiceを作成して実装します。

    export default class DemoNotificationService {
        constructor(
            readonly apiUrl: string,
            readonly apiKey: string) {
        }
    
    async registerAsync(request: any): Promise<Response> {
            const method = 'PUT';
            const registerApiUrl = `${this.apiUrl}/notifications/installations`;
            const result = await fetch(registerApiUrl, {
                method: method,
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'apiKey': this.apiKey
                },
                body: JSON.stringify(request)
            });
    
            this.validateResponse(registerApiUrl, method, request, result);
            return result;
        }
    
        async deregisterAsync(deviceId: string): Promise<Response> {
            const method = 'DELETE';
            const deregisterApiUrl = `${this.apiUrl}/notifications/installations/${deviceId}`;
            const result = await fetch(deregisterApiUrl, {
                method: method,
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'apiKey': this.apiKey
                }
            });
    
            this.validateResponse(deregisterApiUrl, method, null, result);
            return result;
        }
    
        private validateResponse(requestUrl: string, method: string, requestPayload: any, response: Response) {
            console.log(`Request: ${method} ${requestUrl} => ${JSON.stringify(requestPayload)}\nResponse: ${response.status}`);
            if (!response || response.status != 200) {
                throw `HTTP error ${response.status}: ${response.statusText}`;
            }
        }
    }
    
  4. アプリを構成します。 package.json を開き、次のスクリプト定義を追加します。

    "configure": "cp .app.config.tsx src/config/AppConfig.tsx"
    

    次に、このスクリプトを実行します。これにより、既定の構成が config フォルダーにコピーされます。

    yarn configure
    

    最後の手順では、前の手順でコピーした構成ファイルを API アクセス情報で更新します。 apiKey パラメーターと apiUrl パラメーターを指定します。

    module.exports = {
        appName: "PushDemo",
        env: "production",
        apiUrl: "https://<azure-push-notifications-api-url>/api/",
        apiKey: "<api-auth-key>",
    };
    

クロスプラットフォーム UI を実装する

  1. ページ レイアウトの定義

    <View style={styles.container}>
      {this.state.isBusy &&
        <ActivityIndicator></ActivityIndicator>
      }
      <View style={styles.button}>
        <Button title="Register" onPress={this.onRegisterButtonPress.bind(this)} disabled={this.state.isBusy} />
      </View>
      <View style={styles.button}>
        <Button title="Deregister" onPress={this.onDeregisterButtonPress.bind(this)} disabled={this.state.isBusy} />
      </View>
    </View>
    
  2. スタイルを適用する

    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: "center",
        justifyContent: 'flex-end',
        margin: 50,
      },
      button: {
        margin: 5,
        width: "100%",
      }
    });
    
  3. ページ コンポーネントを初期化する

      state: IState;
      notificationService: DemoNotificationService;
      notificationRegistrationService: DemoNotificationRegistrationService;
      deviceId: string;
    
      constructor(props: any) {
        super(props);
        this.deviceId = DeviceInfo.getUniqueId();
        this.state = {
          status: "Push notifications registration status is unknown",
          registeredOS: "",
          registeredToken: "",
          isRegistered: false,
          isBusy: false,
        };
    
        this.notificationService = new DemoNotificationService(
          this.onTokenReceived.bind(this),
          this.onNotificationReceived.bind(this),
        );
    
        this.notificationRegistrationService = new DemoNotificationRegistrationService(
          Config.apiUrl,
          Config.apiKey,
        );
      }
    
  4. ボタン クリック ハンドラーを定義する

      async onRegisterButtonPress() {
        if (!this.state.registeredToken || !this.state.registeredOS) {
          Alert.alert("The push notifications token wasn't received.");
          return;
        }
    
        let status: string = "Registering...";
        let isRegistered = this.state.isRegistered;
        try {
          this.setState({ isBusy: true, status });
          const pnPlatform = this.state.registeredOS == "ios" ? "apns" : "fcm";
          const pnToken = this.state.registeredToken;
          const request = {
            installationId: this.deviceId,
            platform: pnPlatform,
            pushChannel: pnToken,
            tags: []
          };
          const response = await this.notificationRegistrationService.registerAsync(request);
          status = `Registered for ${this.state.registeredOS} push notifications`;
          isRegistered = true;
        } catch (e) {
          status = `Registration failed: ${e}`;
        }
        finally {
          this.setState({ isBusy: false, status, isRegistered });
        }
      }
    
      async onDeregisterButtonPress() {
        if (!this.notificationService)
          return;
    
        let status: string = "Deregistering...";
        let isRegistered = this.state.isRegistered;
        try {
          this.setState({ isBusy: true, status });
          await this.notificationRegistrationService.deregisterAsync(this.deviceId);
          status = "Deregistered from push notifications";
          isRegistered = false;
        } catch (e) {
          status = `Deregistration failed: ${e}`;
        }
        finally {
          this.setState({ isBusy: false, status, isRegistered });
        }
      }
    
  5. 受信したトークンの登録とプッシュ通知を処理する

      onTokenReceived(token: any) {
        console.log(`Received a notification token on ${token.os}`);
        this.setState({ registeredToken: token.token, registeredOS: token.os, status: `The push notifications token has been received.` });
    
        if (this.state.isRegistered && this.state.registeredToken && this.state.registeredOS) {
          this.onRegisterButtonPress();
        }
      }
    
      onNotificationReceived(notification: any) {
        console.log(`Received a push notification on ${this.state.registeredOS}`);
        this.setState({ status: `Received a push notification...` });
    
        if (notification.data.message) {
          Alert.alert(AppConfig.appName, `${notification.data.action} action received`);
        }
      }
    };
    

プッシュ通知用にネイティブ Android プロジェクトを構成する

必要な Android パッケージを構成する

パッケージは、アプリのビルド時に自動的にリンク 。 構成プロセスを完了するには、以下のいくつかの追加手順があります。

Android マニフェストを構成する

"android/app/src/main/AndroidManifest.xml" で、パッケージ名、アクセス許可、および必要なサービスを確認します。 RNPushNotificationPublisherRNPushNotificationBootEventReceiver レシーバーを登録し、RNPushNotificationListenerService サービスを登録したことを確認します。 通知メタデータを使用して、プッシュ通知の外観をカスタマイズできます。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="YOUR_PACKAGE_NAME">

      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.WAKE_LOCK" />
      <uses-permission android:name="android.permission.VIBRATE" />
      <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

      <application
        android:name=".MainApplication"
        android:label="@string/app_name"
        android:usesCleartextTraffic="true"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:allowBackup="false"
        android:theme="@style/AppTheme">

        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_name"
                    android:value="PushDemo Channel"/>
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_channel_description"
                    android:value="PushDemo Channel Description"/>
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_foreground"
                    android:value="true"/>
        <meta-data  android:name="com.dieam.reactnativepushnotification.notification_color"
                    android:resource="@android:color/white"/>

        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationPublisher" />
        <receiver android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationBootEventReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <service
            android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <activity
          android:name=".MainActivity"
          android:label="@string/app_name"
          android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
          android:launchMode="singleTask"
          android:windowSoftInputMode="adjustResize">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
      </application>

</manifest>

Google サービスを構成する

"android/app/build.gradle" で Google Services を登録します。

dependencies {
  ...
  implementation 'com.google.firebase:firebase-analytics:17.3.0'
  ...
}

apply plugin: 'com.google.gms.google-services'

FCM セットアップ中にダウンロードした "google-services.json" ファイルをプロジェクト フォルダー "android/app/" にコピーします。

Android のプッシュ通知を処理する

受信した Android プッシュ通知を処理するように既存の RNPushNotificationListenerService サービスを構成しました。 このサービスは、先ほどアプリケーション マニフェストに登録されました。 受信通知を処理し、クロスプラットフォーム React Native パーツにプロキシします。 追加の手順は必要ありません。

プッシュ通知用にネイティブ iOS プロジェクトを構成する

必要な iOS パッケージを構成する

パッケージは、アプリのビルド時に自動的にリンク 。 必要なのは、ネイティブ ポッドをインストールするだけです。

npx pod-install

Info.plist と Entitlements.plist の構成

  1. "PushDemo/ios" フォルダーに移動し、"PushDemo.xcworkspace" ワークスペースを開き、上部のプロジェクト "PushDemo" を選択し、[署名 & 機能] タブを選択します。

  2. プロビジョニング プロファイルで使用される値と一致するようにバンドル識別子を更新します。

  3. [+] ボタンを使用して 2 つの新しい機能を追加します。

    • バックグラウンドモード機能とチェックリモート通知。
    • プッシュ通知機能

iOS のプッシュ通知を処理する

  1. "AppDelegate.h" を開き、次のインポートを追加します。

    #import <UserNotifications/UNUserNotificationCenter.h>
    
  2. UNUserNotificationCenterDelegateを追加して、"AppDelegate" でサポートされているプロトコルの一覧を更新します。

    @interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate>
    
  3. "AppDelegate.m" を開き、必要なすべての iOS コールバックを構成します。

    #import <UserNotifications/UserNotifications.h>
    #import <RNCPushNotificationIOS.h>
    
    ...
    
    // Required to register for notifications
    - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
    {
     [RNCPushNotificationIOS didRegisterUserNotificationSettings:notificationSettings];
    }
    
    // Required for the register event.
    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
    {
     [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    }
    
    // Required for the notification event. You must call the completion handler after handling the remote notification.
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
    {
      [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
    }
    
    // Required for the registrationError event.
    - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
    {
     [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
    }
    
    // IOS 10+ Required for localNotification event
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center
    didReceiveNotificationResponse:(UNNotificationResponse *)response
             withCompletionHandler:(void (^)(void))completionHandler
    {
      [RNCPushNotificationIOS didReceiveNotificationResponse:response];
      completionHandler();
    }
    
    // IOS 4-10 Required for the localNotification event.
    - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
    {
     [RNCPushNotificationIOS didReceiveLocalNotification:notification];
    }
    
    //Called when a notification is delivered to a foreground app.
    -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
    {
      completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
    }
    

ソリューションをテストする

バックエンド サービスを介した通知の送信をテストできるようになりました。

テスト通知を送信する

  1. Postmanで新しいタブ 開きます。

  2. 要求を POSTに設定し、次のアドレスを入力します。

    https://<app_name>.azurewebsites.net/api/notifications/requests
    
  3. API キー セクションを使用してクライアントを認証する を完了する場合は、apikey 値を含めるように要求ヘッダーを構成してください。

    価値
    apikey <your_api_key>
  4. Bodyraw オプションを選択し、書式設定オプションの一覧から JSON 選択し、JSON コンテンツ プレースホルダーを含めます。

    {
        "text": "Message from Postman!",
        "action": "action_a"
    }
    
  5. ウィンドウの右上にある [ の保存] ボタンの下にある [Code] ボタンを選択します。 要求は、HTML に対して表示される場合の次の例のようになります (apikey ヘッダーを含めたかどうかによって異なります)。

    POST /api/notifications/requests HTTP/1.1
    Host: https://<app_name>.azurewebsites.net
    apikey: <your_api_key>
    Content-Type: application/json
    
    {
        "text": "Message from backend service",
        "action": "action_a"
    }
    
  6. PushDemo アプリケーションを、ターゲット プラットフォームの一方または両方 (AndroidiOS) で実行します。

    手記

    Android でテストデバッグで実行されていないことを確認するか、アプリケーションを実行してアプリがデプロイされている場合は、アプリを強制的に閉じて起動ツールから再度起動します。

  7. PushDemo アプリで、[Register] ボタンをタップします。

  8. Postman戻り、[コード スニペットの生成] ウィンドウを閉じて (まだ行っていない場合)、[ の送信] ボタンをクリックします。

  9. Postman で 200 OK 応答 受け取り、アラートがアプリに表示され、受け取った ActionA アクション 表示されていることを確認します。

  10. PushDemo アプリを閉じ、Postmanでもう一度 [送信] ボタン クリックします。

  11. Postman で 200 OK 応答 返されることを検証します。 正しいメッセージを含む PushDemo アプリの通知領域に通知が表示されることを確認します。

  12. 通知をタップしてアプリを開き、アラート 受け取った ActionA アクションを表示したことを確認します。

  13. Postman戻り、前の要求本文を変更して、アクションの 値に action_a するのではなく、action_b を指定するサイレント通知を送信します。

    {
        "action": "action_b",
        "silent": true
    }
    
  14. アプリを開いたまま、Postmanの [送信] ボタン クリックします。

  15. Postman で 200 OK 応答を受け取り、受け取った ActionA アクションではなく、 を受け取った ActionB アクション 示すアラート アプリに表示されることを検証します。

  16. PushDemo アプリを閉じ、Postmanでもう一度 [送信] ボタン クリックします。

  17. Postman で 200 OK 応答 受け取り、通知領域にサイレント通知が表示されないかどうかを検証します。

トラブルシューティング

バックエンド サービスからの応答なし

ローカルでテストする場合は、バックエンド サービスが実行されており、正しいポートを使用していることを確認します。

Azure API Appに対してテストする場合は、サービスが実行中であり、デプロイされていて、エラーなしで開始されていることを確認します。

クライアント経由でテストする場合は、Postman またはモバイル アプリ構成 ベース アドレスが正しく指定されていることを確認してください。 ローカルでテストする場合は、ベース アドレスを https://<api_name>.azurewebsites.net/ または https://localhost:5001/ する必要があります。

デバッグ セッションの開始または停止後に Android で通知を受信しない

デバッグ セッションを開始または停止した後に、もう一度登録してください。 デバッガーによって、新しい Firebase トークンが生成されます。 通知ハブのインストールも更新する必要があります。

バックエンド サービスからの 401 状態コードの受信

apikey 要求ヘッダーを設定していることを確認します。この値は、バックエンド サービス用に構成したものと一致します。

ローカルでテストするときにこのエラーが発生した場合は、クライアント構成で定義したキー値が、APIで使用される Authentication:ApiKey ユーザー設定値と一致していることを確認します。

API アプリを使用してテストする場合は、クライアント構成ファイルのキー値が、API アプリで使用している Authentication:ApiKey アプリケーション設定と一致していることを確認します。

手記

バックエンド サービスをデプロイした後にこの設定を作成または変更した場合は、サービスを有効にするためにサービスを再起動する必要があります。

API キー セクションを使用してクライアントの認証 を完了しないことを選択した場合は、NotificationsController クラスに Authorize 属性を適用していないことを確認します。

バックエンド サービスからの 404 状態コードの受信

エンドポイントと HTTP 要求メソッドが正しいことを検証します。 たとえば、エンドポイントは次のように示す必要があります。

  • [PUT]する
  • [DELETE]https://<api_name>.azurewebsites.net/api/notifications/installations/<installation_id>
  • [POST]https://<api_name>.azurewebsites.net/api/notifications/requests

または、ローカルでテストする場合:

  • [PUT]する
  • [DELETE]https://localhost:5001/api/notifications/installations/<installation_id>
  • [POST]https://localhost:5001/api/notifications/requests

クライアント アプリでベース アドレスを指定するときは、/で終わることを確認します。 ローカルでテストする場合は、ベース アドレスを https://<api_name>.azurewebsites.net/ または https://localhost:5001/ する必要があります。

登録できず、通知ハブのエラー メッセージが表示される

テスト デバイスにネットワーク接続があることを確認します。 次に、HttpResponseStatusCode プロパティ値を検査するブレークポイントを設定して、Http 応答状態コードを決定します。

状態コードに基づいて、該当する場合は、前のトラブルシューティングの推奨事項を確認します。

それぞれの API に対してこれらの特定の状態コードを返す行にブレークポイントを設定します。 次に、ローカルでデバッグするときにバックエンド サービスを呼び出してみてください。

適切なペイロードを使用 Postman を使用して、バックエンド サービスが期待どおりに動作していることを確認します。 対象のプラットフォームのクライアント コードによって作成された実際のペイロードを使用します。

プラットフォーム固有の構成セクションを確認して、手順が実行されていないことを確認します。 適切なプラットフォームの installation id 変数と token 変数に対して適切な値が解決されていることを確認します。

デバイスの ID を解決できないエラー メッセージが表示される

プラットフォーム固有の構成セクションを確認して、手順が実行されていないことを確認します。

次の手順

これで、バックエンド サービスを介して通知ハブに接続され、通知を送受信できる基本的な React Native アプリが作成されました。

このチュートリアルで使用する例を独自のシナリオに合わせて調整する必要がある可能性があります。 より堅牢なエラー処理、再試行ロジック、ログ記録の実装も推奨されます。

Visual Studio App Center は、トラブルシューティングに役立つ 分析診断 を提供するモバイル アプリにすばやく組み込むことができます。