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

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

このチュートリアルでは、Azure Notification Hubs を使用して、AndroidiOS を対象とする Xamarin.Forms アプリケーションに通知をプッシュします。

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

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

このチュートリアルでは、次の手順について説明します。

前提条件

作業を進めるためには、次が必要です。

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

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

  • 開発者が物理デバイスまたはエミュレーターのロックを解除しました (Google Play Services がインストールされた API 26 以降を実行しています)。

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

注意

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

この最初の原則の例の手順に従うことができますが、以前の経験はありません。 ただし、次の点に精通するとメリットがあります。

重要

提供される手順は、Visual Studio for Macに固有のものです。 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 アプリに追加する] を選択します。

    Android アプリに Firebase を追加する

  3. [ Android アプリへの Firebase の追加] ページで、次の手順を実行します。

    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: com.organization_identifier<> フォームのバンドル ID を入力します。<>product_nameアプリ配布ガイドで説明されているようにします。 次のスクリーンショットでは、mobcat値がorganization識別子として使用され、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. [ユーザー Email アドレス] を選択し、[共通名] の値を入力し、[ディスクに保存] を指定したことを確認してから、[続行] を選択しますCA Email アドレスは不要であるため、空白のままにします。

    予想される証明書情報

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

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

    このアクションにより、選択した場所に CSR ファイル が保存されます。 既定の場所は Desktop です。 ファイルに対して選択した場所を思い出してください。

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

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

  6. [Apple Push Notification service TLS/SSL Certificates]\(Apple プッシュ通知サービスの TLS/SSL 証明書\) ウィンドウが表示されます。 [開発 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 証明書を再利用できます。 その場合は、手順 3 から 5 を無視できます。

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

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

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

    注意

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

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

  7. [キー ID] の値をメモします。

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

    -----BEGIN 秘密キー-----
    <key_value>
    -----END 秘密キー-----

    注意

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

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

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

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

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

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

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

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

    アプリ ID を選択する

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

    注意

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

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

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

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

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

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

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

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

通知ハブの作成

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

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

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

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

    基本的な詳細

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

    名前空間の詳細

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

    注意

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

    通知ハブの詳細

    通知ハブ:通知ハブの名前を入力します
    場所: ドロップダウン リストから適切な場所を選択する
    価格レベル: 既定の [無料] オプションをそのまま使用する

    注意

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

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

  5. 新しい 通知ハブに移動します。

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

  7. ポリシー名の値とそれに対応する接続文字列の値をメモしておきます。

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

[ Notification Services]\(通知サービス\) で[Apple]\( Apple \) を選択し、[ Creating a Certificate for Notification Hubs]\(通知ハブの証明書の作成 \) セクションで前に選択したアプローチに基づいて適切な手順に従います。

注意

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

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

  1. [Certificate] を選択します。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  2. [.NET Core>アプリ>ASP.NET Core>API> Next] を選択します

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

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

  5. デバッグを開始して (Command + Enter) テンプレート アプリをテストします。

    注意

    テンプレート化されたアプリは、 weatherForecastControllerlaunchUrl として使用するように構成されています。 これは、[プロパティ] 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:
    概要の上部にある「要点の概要」の「名前」を参照してください。

    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. 別の Empty クラスApiKeyAuthHandler.cs という名前の認証フォルダーに追加し、次の実装を追加します。

    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. ApiKeyAuthenticationBuilderExtensions.cs という名前の認証フォルダーに別の Empty クラスを追加し、次の実装を追加します。

    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、アプリの IApplicationBuilderUseAuthentication および UseAuthorization 拡張メソッドを呼び出すように Configure メソッドを更新します。 これらのメソッドは、 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. コントロール + [依存関係] フォルダーをクリックし、[NuGet パッケージの管理...] を選択します。

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

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

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

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

  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 フォルダーに別の Empty クラスを追加し、次の実装を追加します。

    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 フォルダーに別の Empty クラスを追加し、次の実装を追加します。

    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 フォルダーに別の Empty クラスを追加し、次の実装を追加します。

    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 という名前の [サービス] フォルダーに空のインターフェイスを追加し、次の実装を追加します。

    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 メソッドを更新して、NotificationHubsServiceINotificationService のシングルトン実装として追加します。

    
    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. [ASP.NET Core>Web API コントローラー クラス] を選択し、[名前]「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 ([プロパティ] フォルダー内) で、registrationsControllerRoute 属性で指定された URL と一致するように launchUrl を から weatherforecastapi/notifications に変更します。

  8. デバッグを開始し (Command + 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. [ 送信 ] ボタンをクリックします。

    注意

    JSON コンテンツを含む 200 OK 状態を受け取る必要があります。

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

  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 アプリをAzure App Serviceに作成します。

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

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

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

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

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

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

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

    注意

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

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

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

  5. [概要] の上部にある [要点] の概要にある 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 でフォローしている場合、発行フローは異なります。 「Windows でAzure App Serviceに発行する」を参照してください。

  1. まだ行っていない場合は、構成を [デバッグ] から [リリース ] に変更します。

  2. コントロール + PushDemoApi プロジェクトをクリックし、[発行] メニューから [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. [本文] ののオプションを選択し、形式オプションの一覧から [JSON] を選択し、いくつかのプレースホルダー JSON コンテンツを含めます。

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

    注意

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

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

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

注意

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

クロスプラットフォーム Xamarin.Forms アプリケーションを作成する

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

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

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

注意

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

Xamarin.Forms ソリューションを作成する

  1. Visual Studio で、空のフォーム アプリをテンプレートとして使用し、プロジェクト名PushDemo を入力して、新しい Xamarin.Forms ソリューションを作成します。

    注意

    [ 空のフォーム アプリの構成 ] ダイアログで、 組織識別子 が前に使用した値と一致し、 AndroidiOS の両方のターゲットがチェックされていることを確認します。

  2. コントロール + PushDemo ソリューションをクリックし、[NuGet パッケージの更新] を選択します。

  3. コントロール + PushDemo ソリューションをクリックし、[NuGet パッケージの管理]を選択します。

  4. Newtonsoft.Json を検索し、チェックされていることを確認します。

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

  6. 各ターゲット プラットフォーム (Command + Enter) でアプリをビルドして実行し、デバイスでテンプレート化されたアプリの実行をテストします。

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

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

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

  3. [全般空のクラス]> を選択し、「DeviceInstallation.cs」と入力し、次の実装を追加します。

    using System.Collections.Generic;
    using Newtonsoft.Json;
    
    namespace PushDemo.Models
    {
        public class DeviceInstallation
        {
            [JsonProperty("installationId")]
            public string InstallationId { get; set; }
    
            [JsonProperty("platform")]
            public string Platform { get; set; }
    
            [JsonProperty("pushChannel")]
            public string PushChannel { get; set; }
    
            [JsonProperty("tags")]
            public List<string> Tags { get; set; } = new List<string>();
        }
    }
    
  4. 次の実装を使用して、PushDemoAction.cs という名前の Models フォルダーに空の列挙を追加します。

    namespace PushDemo.Models
    {
        public enum PushDemoAction
        {
            ActionA,
            ActionB
        }
    }
    
  5. Services という名前の PushDemo プロジェクトに新しいフォルダーを追加し、次の実装で ServiceContainer.cs という名前のそのフォルダーに Empty クラスを追加します。

    using System;
    using System.Collections.Generic;
    
    namespace PushDemo.Services
    {
       public static class ServiceContainer
       {
           static readonly Dictionary<Type, Lazy<object>> services
               = new Dictionary<Type, Lazy<object>>();
    
           public static void Register<T>(Func<T> function)
               => services[typeof(T)] = new Lazy<object>(() => function());
    
           public static T Resolve<T>()
               => (T)Resolve(typeof(T));
    
           public static object Resolve(Type type)
           {
               {
                   if (services.TryGetValue(type, out var service))
                       return service.Value;
    
                   throw new KeyNotFoundException($"Service not found for type '{type}'");
               }
           }
       }
    }
    

    注意

    これは、XamCAT リポジトリの ServiceContainer クラスのトリミングされたバージョンです。 軽量の IoC (制御の反転) コンテナーとして使用されます。

  6. [IDeviceInstallationService.cs] という名前の [サービス] フォルダーに空のインターフェイスを追加し、次のコードを追加します。

    using PushDemo.Models;
    
    namespace PushDemo.Services
    {
        public interface IDeviceInstallationService
        {
            string Token { get; set; }
            bool NotificationsSupported { get; }
            string GetDeviceId();
            DeviceInstallation GetDeviceInstallation(params string[] tags);
        }
    }
    

    注意

    このインターフェイスは、バックエンド サービスに必要なプラットフォーム固有の機能と DeviceInstallation 情報を提供するために、後で各ターゲットによって実装およびブートストラップされます。

  7. INotificationRegistrationService.cs という名前の別の空のインターフェイスServices フォルダーに追加し、次のコードを追加します。

    using System.Threading.Tasks;
    
    namespace PushDemo.Services
    {
        public interface INotificationRegistrationService
        {
            Task DeregisterDeviceAsync();
            Task RegisterDeviceAsync(params string[] tags);
            Task RefreshRegistrationAsync();
        }
    }
    

    注意

    これにより、クライアントとバックエンド サービスの間の相互作用が処理されます。

  8. INotificationActionService.cs という名前の別の空のインターフェイスServices フォルダーに追加し、次のコードを追加します。

    namespace PushDemo.Services
    {
        public interface INotificationActionService
        {
            void TriggerAction(string action);
        }
    }
    

    注意

    これは、通知アクションの処理を一元化するための簡単なメカニズムとして使用されます。

  9. 次の実装を使用して、INotificationActionService から派生した IPushDemoNotificationActionService.cs という名前のサービス フォルダーに空のインターフェイスを追加します。

    using System;
    using PushDemo.Models;
    
    namespace PushDemo.Services
    {
        public interface IPushDemoNotificationActionService : INotificationActionService
        {
            event EventHandler<PushDemoAction> ActionTriggered;
        }
    }
    

    注意

    この型は PushDemo アプリケーションに固有であり、 PushDemoAction 列挙を使用して、厳密に型指定された方法でトリガーされるアクションを識別します。

  10. 次のコードを使用して、INotificationRegistrationServiceを実装NotificationRegistrationService.csという名前の空のクラスServices フォルダーに追加します。

    using System;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using PushDemo.Models;
    using Xamarin.Essentials;
    
    namespace PushDemo.Services
    {
        public class NotificationRegistrationService : INotificationRegistrationService
        {
            const string RequestUrl = "api/notifications/installations";
            const string CachedDeviceTokenKey = "cached_device_token";
            const string CachedTagsKey = "cached_tags";
    
            string _baseApiUrl;
            HttpClient _client;
            IDeviceInstallationService _deviceInstallationService;
    
            public NotificationRegistrationService(string baseApiUri, string apiKey)
            {
                _client = new HttpClient();
                _client.DefaultRequestHeaders.Add("Accept", "application/json");
                _client.DefaultRequestHeaders.Add("apikey", apiKey);
    
                _baseApiUrl = baseApiUri;
            }
    
            IDeviceInstallationService DeviceInstallationService
                => _deviceInstallationService ??
                    (_deviceInstallationService = ServiceContainer.Resolve<IDeviceInstallationService>());
    
            public async Task DeregisterDeviceAsync()
            {
                var cachedToken = await SecureStorage.GetAsync(CachedDeviceTokenKey)
                    .ConfigureAwait(false);
    
                if (cachedToken == null)
                    return;
    
                var deviceId = DeviceInstallationService?.GetDeviceId();
    
                if (string.IsNullOrWhiteSpace(deviceId))
                    throw new Exception("Unable to resolve an ID for the device.");
    
                await SendAsync(HttpMethod.Delete, $"{RequestUrl}/{deviceId}")
                    .ConfigureAwait(false);
    
                SecureStorage.Remove(CachedDeviceTokenKey);
                SecureStorage.Remove(CachedTagsKey);
            }
    
            public async Task RegisterDeviceAsync(params string[] tags)
            {
                var deviceInstallation = DeviceInstallationService?.GetDeviceInstallation(tags);
    
                await SendAsync<DeviceInstallation>(HttpMethod.Put, RequestUrl, deviceInstallation)
                    .ConfigureAwait(false);
    
                await SecureStorage.SetAsync(CachedDeviceTokenKey, deviceInstallation.PushChannel)
                    .ConfigureAwait(false);
    
                await SecureStorage.SetAsync(CachedTagsKey, JsonConvert.SerializeObject(tags));
            }
    
            public async Task RefreshRegistrationAsync()
            {
                var cachedToken = await SecureStorage.GetAsync(CachedDeviceTokenKey)
                    .ConfigureAwait(false);
    
                var serializedTags = await SecureStorage.GetAsync(CachedTagsKey)
                    .ConfigureAwait(false);
    
                if (string.IsNullOrWhiteSpace(cachedToken) ||
                    string.IsNullOrWhiteSpace(serializedTags) ||
                    string.IsNullOrWhiteSpace(DeviceInstallationService.Token) ||
                    cachedToken == DeviceInstallationService.Token)
                    return;
    
                var tags = JsonConvert.DeserializeObject<string[]>(serializedTags);
    
                await RegisterDeviceAsync(tags);
            }
    
            async Task SendAsync<T>(HttpMethod requestType, string requestUri, T obj)
            {
                string serializedContent = null;
    
                await Task.Run(() => serializedContent = JsonConvert.SerializeObject(obj))
                    .ConfigureAwait(false);
    
                await SendAsync(requestType, requestUri, serializedContent);
            }
    
            async Task SendAsync(
                HttpMethod requestType,
                string requestUri,
                string jsonRequest = null)
            {
                var request = new HttpRequestMessage(requestType, new Uri($"{_baseApiUrl}{requestUri}"));
    
                if (jsonRequest != null)
                    request.Content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
    
                var response = await _client.SendAsync(request).ConfigureAwait(false);
    
                response.EnsureSuccessStatusCode();
            }
        }
    }
    

    注意

    apiKey 引数は、[API キーを使用してクライアントを認証する] セクションを完了することを選択した場合にのみ必要です。

  11. 次のコードを使用して、IPushDemoNotificationActionServiceを実装PushDemoNotificationActionService.csという名前の空のクラスServices フォルダーに追加します。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using PushDemo.Models;
    
    namespace PushDemo.Services
    {
        public class PushDemoNotificationActionService : IPushDemoNotificationActionService
        {
            readonly Dictionary<string, PushDemoAction> _actionMappings = new Dictionary<string, PushDemoAction>
            {
                { "action_a", PushDemoAction.ActionA },
                { "action_b", PushDemoAction.ActionB }
            };
    
            public event EventHandler<PushDemoAction> ActionTriggered = delegate { };
    
            public void TriggerAction(string action)
            {
                if (!_actionMappings.TryGetValue(action, out var pushDemoAction))
                    return;
    
                List<Exception> exceptions = new List<Exception>();
    
                foreach (var handler in ActionTriggered?.GetInvocationList())
                {
                    try
                    {
                        handler.DynamicInvoke(this, pushDemoAction);
                    }
                    catch (Exception ex)
                    {
                        exceptions.Add(ex);
                    }
                }
    
                if (exceptions.Any())
                    throw new AggregateException(exceptions);
            }
        }
    }
    
  12. 次の実装を使用して、Config.cs という名前の PushDemo プロジェクトに Empty クラスを追加します。

    namespace PushDemo
    {
        public static partial class Config
        {
            public static string ApiKey = "API_KEY";
            public static string BackendServiceEndpoint = "BACKEND_SERVICE_ENDPOINT";
        }
    }
    

    注意

    これは、シークレットをソース管理から遠ざける簡単な方法として使用されます。 これらの値は、自動ビルドの一部として置き換えたり、ローカル部分クラスを使用してオーバーライドしたりできます。 これは次の手順で行います。

    ApiKey フィールドは、[API キーを使用してクライアントを認証する] セクションを完了することを選択した場合にのみ必要です。

  13. 今回は Config.local_secrets.cs と呼ばれる別の Empty クラスPushDemo プロジェクトに追加し、次の実装を行います。

    namespace PushDemo
    {
        public static partial class Config
        {
            static Config()
            {
                ApiKey = "<your_api_key>";
                BackendServiceEndpoint = "<your_api_app_url>";
            }
        }
    }
    

    注意

    プレースホルダーの値を独自の値に置き換えます。 バックエンド サービスを構築するときに、これらをメモしておく必要があります。 API アプリの URL は であるhttps://<api_app_name>.azurewebsites.net/必要があります。 このファイルのコミットを避けるために、gitignore ファイルに を追加 *.local_secrets.* してください。

    ApiKey フィールドは、[API キーを使用してクライアントを認証する] セクションを完了することを選択した場合にのみ必要です。

  14. 次の実装を使用して、Bootstrap.cs という名前の空のクラスPushDemo プロジェクトに追加します。

    using System;
    using PushDemo.Services;
    
    namespace PushDemo
    {
        public static class Bootstrap
        {
            public static void Begin(Func<IDeviceInstallationService> deviceInstallationService)
            {
                ServiceContainer.Register(deviceInstallationService);
    
                ServiceContainer.Register<IPushDemoNotificationActionService>(()
                    => new PushDemoNotificationActionService());
    
                ServiceContainer.Register<INotificationRegistrationService>(()
                    => new NotificationRegistrationService(
                        Config.BackendServiceEndpoint,
                        Config.ApiKey));
            }
        }
    }
    

    注意

    Begin メソッドは、IDeviceInstallationService のプラットフォーム固有の実装を渡してアプリが起動すると、各プラットフォームによって呼び出されます。

    NotificationRegistrationServiceapiKey コンストラクター引数は、[API キーを使用してクライアントを認証する] セクションを完了することを選択した場合にのみ必要です。

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

  1. PushDemo プロジェクトで MainPage.xaml を開き、StackLayout コントロールを次のように置き換えます。

    <StackLayout VerticalOptions="EndAndExpand"  
                 HorizontalOptions="FillAndExpand"
                 Padding="20,40">
        <Button x:Name="RegisterButton"
                Text="Register"
                Clicked="RegisterButtonClicked" />
        <Button x:Name="DeregisterButton"
                Text="Deregister"
                Clicked="DeregisterButtonClicked" />
    </StackLayout>
    
  2. MainPage.xaml.csで、読み取り専用バッキング フィールドを追加して、INotificationRegistrationService 実装への参照を格納します。

    readonly INotificationRegistrationService _notificationRegistrationService;
    
  3. MainPage コンストラクターで、ServiceContainer を使用して INotificationRegistrationService 実装を解決し、それを notificationRegistrationService バッキング フィールドに割り当てます。

    public MainPage()
    {
        InitializeComponent();
    
        _notificationRegistrationService =
            ServiceContainer.Resolve<INotificationRegistrationService>();
    }
    
  4. 対応する/ Register Deregister メソッドを呼び出す Clicked イベントの RegisterButton ボタンと DeregisterButton ボタンのイベント ハンドラー実装します。

    void RegisterButtonClicked(object sender, EventArgs e)
        => _notificationRegistrationService.RegisterDeviceAsync().ContinueWith((task)
            => { ShowAlert(task.IsFaulted ?
                    task.Exception.Message :
                    $"Device registered"); });
    
    void DeregisterButtonClicked(object sender, EventArgs e)
        => _notificationRegistrationService.DeregisterDeviceAsync().ContinueWith((task)
            => { ShowAlert(task.IsFaulted ?
                    task.Exception.Message :
                    $"Device deregistered"); });
    
    void ShowAlert(string message)
        => MainThread.BeginInvokeOnMainThread(()
            => DisplayAlert("PushDemo", message, "OK").ContinueWith((task)
                => { if (task.IsFaulted) throw task.Exception; }));
    
  5. App.xaml.csで、次の名前空間が参照されていることを確認します。

    using PushDemo.Models;
    using PushDemo.Services;
    using Xamarin.Essentials;
    using Xamarin.Forms;
    
  6. IPushDemoNotificationActionServiceActionTriggered イベントのイベント ハンドラーを実装します。

    void NotificationActionTriggered(object sender, PushDemoAction e)
        => ShowActionAlert(e);
    
    void ShowActionAlert(PushDemoAction action)
        => MainThread.BeginInvokeOnMainThread(()
            => MainPage?.DisplayAlert("PushDemo", $"{action} action received", "OK")
                .ContinueWith((task) => { if (task.IsFaulted) throw task.Exception; }));
    
  7. アプリ コンストラクターで、ServiceContainer を使用して IPushNotificationActionService 実装を解決し、IPushDemoNotificationActionServiceActionTriggered イベントをサブスクライブします。

    public App()
    {
        InitializeComponent();
    
        ServiceContainer.Resolve<IPushDemoNotificationActionService>()
            .ActionTriggered += NotificationActionTriggered;
    
        MainPage = new MainPage();
    }
    

    注意

    これは、プッシュ通知アクションの受信と伝達を示すためだけに使用されます。 通常、これらは、ルート ページMainPage を介してアラートを表示するのではなく、特定のビューに移動したり、データを更新したりするなど、サイレントに処理されます。

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

パッケージ名とアクセス許可を検証する

  1. PushDemo.Android で、[ビルド] セクションから [プロジェクト オプション]、[Android アプリケーション] の順に開きます。

  2. パッケージ名Firebase ConsolePushDemo プロジェクトで使用した値と一致していることを確認します。 パッケージ名の形式com.<organization>.pushdemoは です。

  3. [Android の最小バージョン] をAndroid 8.0 (API レベル 26) に設定し、[ターゲット Android バージョン] を最新の API レベルに設定します。

    注意

    このチュートリアルでは 、API レベル 26 以上 を実行しているデバイスのみがサポートされていますが、古いバージョンを実行しているデバイスをサポートするように拡張できます。

  4. [必要なアクセス許可] で 、INTERNETREAD_PHONE_STATEアクセス許可が有効になっていることを確認します。

  5. [OK]

Xamarin Google Play Services ベースと Xamarin.Firebase.Messaging パッケージを追加する

  1. PushDemo.Android で、[コントロール + ] [パッケージ] フォルダーをクリックし、[NuGet パッケージの管理...] を選択します。

  2. Xamarin.GooglePlayServices.Base (地下室ではない) を検索し、チェックされていることを確認します。

  3. Xamarin.Firebase.Messaging を検索し、チェックされていることを確認します。

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

Google Services JSON ファイルを追加する

  1. コントロール + プロジェクトをPushDemo.Androidクリックし、[追加] メニューから [既存のファイル...] を選択します。

  2. Firebase コンソールPushDemo プロジェクトを設定したときに前にダウンロードしたgoogle-services.json ファイルを選択し、[開く] をクリックします。

  3. メッセージが表示されたら、 ファイルをディレクトリにコピーすることを選択します

  4. コントロール + プロジェクト内からgoogle-services.json ファイルをPushDemo.Androidクリックし、GoogleServicesJsonビルド アクションとして設定されていることを確認します。

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

  1. コントロール + プロジェクトをPushDemo.Androidクリックし、[追加] メニューの [新しいフォルダー] を選択し、[フォルダー名] として [サービスを使用して追加] をクリックします。

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

  3. [全般>空のクラス] を選択し、[名前] に「DeviceInstallationService.cs」と入力し、[新規] をクリックして次の実装を追加します。

    using System;
    using Android.App;
    using Android.Gms.Common;
    using PushDemo.Models;
    using PushDemo.Services;
    using static Android.Provider.Settings;
    
    namespace PushDemo.Droid.Services
    {
        public class DeviceInstallationService : IDeviceInstallationService
        {
            public string Token { get; set; }
    
            public bool NotificationsSupported
                => GoogleApiAvailability.Instance
                    .IsGooglePlayServicesAvailable(Application.Context) == ConnectionResult.Success;
    
            public string GetDeviceId()
                => Secure.GetString(Application.Context.ContentResolver, Secure.AndroidId);
    
            public DeviceInstallation GetDeviceInstallation(params string[] tags)
            {
                if (!NotificationsSupported)
                    throw new Exception(GetPlayServicesError());
    
                if (string.IsNullOrWhiteSpace(Token))
                    throw new Exception("Unable to resolve token for FCM");
    
                var installation = new DeviceInstallation
                {
                    InstallationId = GetDeviceId(),
                    Platform = "fcm",
                    PushChannel = Token
                };
    
                installation.Tags.AddRange(tags);
    
                return installation;
            }
    
            string GetPlayServicesError()
            {
                int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(Application.Context);
    
                if (resultCode != ConnectionResult.Success)
                    return GoogleApiAvailability.Instance.IsUserResolvableError(resultCode) ?
                               GoogleApiAvailability.Instance.GetErrorString(resultCode) :
                               "This device is not supported";
    
                return "An error occurred preventing the use of push notifications";
            }
        }
    }
    

    注意

    このクラスは、通知ハブ登録ペイロードの一部として一意の ID ( Secure.AndroidId を使用) を提供します。

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

    using Android.App;
    using Android.Content;
    using Firebase.Messaging;
    using PushDemo.Services;
    
    namespace PushDemo.Droid.Services
    {
        [Service]
        [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
        public class PushNotificationFirebaseMessagingService : FirebaseMessagingService
        {
            IPushDemoNotificationActionService _notificationActionService;
            INotificationRegistrationService _notificationRegistrationService;
            IDeviceInstallationService _deviceInstallationService;
    
            IPushDemoNotificationActionService NotificationActionService
                => _notificationActionService ??
                    (_notificationActionService =
                    ServiceContainer.Resolve<IPushDemoNotificationActionService>());
    
            INotificationRegistrationService NotificationRegistrationService
                => _notificationRegistrationService ??
                    (_notificationRegistrationService =
                    ServiceContainer.Resolve<INotificationRegistrationService>());
    
            IDeviceInstallationService DeviceInstallationService
                => _deviceInstallationService ??
                    (_deviceInstallationService =
                    ServiceContainer.Resolve<IDeviceInstallationService>());
    
            public override void OnNewToken(string token)
            {
                DeviceInstallationService.Token = token;
    
                NotificationRegistrationService.RefreshRegistrationAsync()
                    .ContinueWith((task) => { if (task.IsFaulted) throw task.Exception; });
            }
    
            public override void OnMessageReceived(RemoteMessage message)
            {
                if(message.Data.TryGetValue("action", out var messageAction))
                    NotificationActionService.TriggerAction(messageAction);
            }
        }
    }
    
  5. MainActivity.csで、次の名前空間がファイルの先頭に追加されていることを確認します。

    using System;
    using Android.App;
    using Android.Content;
    using Android.Content.PM;
    using Android.OS;
    using Android.Runtime;
    using Firebase.Iid;
    using PushDemo.Droid.Services;
    using PushDemo.Services;
    
  6. MainActivity.csでは、LaunchModeSingleTop に設定して、MainActivity が開いたときに再び作成されないようにします。

    [Activity(
        Label = "PushDemo",
        LaunchMode = LaunchMode.SingleTop,
        Icon = "@mipmap/icon",
        Theme = "@style/MainTheme",
        MainLauncher = true,
        ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    
  7. プライベート プロパティと対応するバッキング フィールドを追加して、 IPushNotificationActionService および IDeviceInstallationService 実装への参照を格納します。

    IPushDemoNotificationActionService _notificationActionService;
    IDeviceInstallationService _deviceInstallationService;
    
    IPushDemoNotificationActionService NotificationActionService
        => _notificationActionService ??
            (_notificationActionService =
            ServiceContainer.Resolve<IPushDemoNotificationActionService>());
    
    IDeviceInstallationService DeviceInstallationService
        => _deviceInstallationService ??
            (_deviceInstallationService =
            ServiceContainer.Resolve<IDeviceInstallationService>());
    
  8. IOnSuccessListener インターフェイスを実装して、Firebase トークンを取得して格納します。

    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, Android.Gms.Tasks.IOnSuccessListener
    {
        ...
    
        public void OnSuccess(Java.Lang.Object result)
            => DeviceInstallationService.Token =
                result.Class.GetMethod("getToken").Invoke(result).ToString();
    }
    
  9. 指定された意図に action という名前の追加値があるかどうかをチェックする ProcessNotificationActions という名前の新しいメソッドを追加しますIPushDemoNotificationActionService 実装を使用して、そのアクションを条件付きでトリガーします。

    void ProcessNotificationActions(Intent intent)
    {
        try
        {
            if (intent?.HasExtra("action") == true)
            {
                var action = intent.GetStringExtra("action");
    
                if (!string.IsNullOrEmpty(action))
                    NotificationActionService.TriggerAction(action);
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message);
        }
    }
    
  10. OnNewIntent メソッドをオーバーライドして ProcessNotificationActions メソッドを呼び出します。

    protected override void OnNewIntent(Intent intent)
    {
        base.OnNewIntent(intent);
        ProcessNotificationActions(intent);
    }
    

    注意

    アクティビティLaunchModeSingleTop に設定されているため、OnCreate メソッドではなく OnNewIntent メソッドを使用してインテントが既存の Activity インスタンスに送信されるため、OnCreate メソッドと OnNewIntent メソッドの両方で受信インテントを処理する必要があります。

  11. OnCreate メソッドを更新して、呼び出しの直後に を呼び出Bootstrap.Beginしてbase.OnCreateIDeviceInstallationService のプラットフォーム固有の実装を渡します。

    Bootstrap.Begin(() => new DeviceInstallationService());
    
  12. 同じメソッドで、 への呼び出しの直後に、FirebaseApp インスタンスで GetInstanceId を条件付きで呼び出Bootstrap.Beginし、MainActivity をIOnSuccessListener として追加します。

    if (DeviceInstallationService.NotificationsSupported)
    {
        FirebaseInstanceId.GetInstance(Firebase.FirebaseApp.Instance)
            .GetInstanceId()
            .AddOnSuccessListener(this);
    }
    
  13. 引き続き OnCreate で、呼び出しの直後に ProcessNotificationActions を呼び出して LoadApplication 、現在のインテントを渡 します

    ...
    
    LoadApplication(new App());
    
    ProcessNotificationActions(Intent);
    

注意

アプリを実行するたびに再登録し、デバッグ セッションから停止して、プッシュ通知の受信を続ける必要があります。

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

Info.plist と Entitlements.plist を構成する

  1. Visual Studio> 環境設定で Apple Developer アカウントにサインインしていることを確認します。>公開>Apple Developer アカウントと適切な証明書プロビジョニング プロファイルがダウンロードされました。 これらの資産は、前の手順の一部として作成しておく必要があります。

  2. PushDemo.iOSInfo.plist を開き、BundleIdentifierApple 開発者ポータルのそれぞれのプロビジョニング プロファイルに使用された値と一致していることを確認します。 BundleIdentifier の形式com.<organization>.PushDemoは です。

  3. 同じファイルで、[ 最小システム バージョン]13.0 に設定します。

    注意

    このチュートリアルでは 、iOS 13.0 以降 を実行しているデバイスのみがサポートされていますが、古いバージョンを実行しているデバイスをサポートするように拡張できます。

  4. PushDemo.iOS[プロジェクト オプション] を開きます (プロジェクトをダブルクリックします)。

  5. [プロジェクト オプション] の [Build iOS Bundle Signing]\(iOS バンドル署名のビルド>\) で、[Team]\(チーム\) で開発者アカウントが選択されていることを確認します。 次に、[署名の自動管理] が選択され、署名証明書とプロビジョニング プロファイルが自動的に選択されていることを確認します。

    注意

    署名証明書プロビジョニング プロファイルが自動的に選択されていない場合は、[手動プロビジョニング] を選択し、[バンドル署名オプション] をクリックします。 [署名 ID][チーム] が選択され、デバッグ構成とリリース構成の両方で [プロビジョニング プロファイル] に PushDemo 固有のプロビジョニング プロファイルが選択されていることを確認し、どちらの場合も iPhoneプラットフォームに対して選択されていることを確認します。

  6. PushDemo.iOSEntitlements.plist を開き、[エンタイトルメント] タブで [プッシュ通知を有効にする] がオンになっていることを確認します。次に、[ソース] タブで [APS Environment]\(APS 環境設定\) が [development]\(開発\) に設定されていることを確認します。

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

  1. コントロール + PushDemo.iOS プロジェクトをクリックし、[追加] メニューから [新しいフォルダー] を選択し、フォルダー名として [サービスを使用して追加] をクリックします。

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

  3. [全般>空のクラス] を選択し、[名前] に「DeviceInstallationService.cs」と入力し、[新規] をクリックして次の実装を追加します。

    using System;
    using PushDemo.Models;
    using PushDemo.Services;
    using UIKit;
    
    namespace PushDemo.iOS.Services
    {
        public class DeviceInstallationService : IDeviceInstallationService
        {
            const int SupportedVersionMajor = 13;
            const int SupportedVersionMinor = 0;
    
            public string Token { get; set; }
    
            public bool NotificationsSupported
                => UIDevice.CurrentDevice.CheckSystemVersion(SupportedVersionMajor, SupportedVersionMinor);
    
            public string GetDeviceId()
                => UIDevice.CurrentDevice.IdentifierForVendor.ToString();
    
            public DeviceInstallation GetDeviceInstallation(params string[] tags)
            {
                if (!NotificationsSupported)
                    throw new Exception(GetNotificationsSupportError());
    
                if (string.IsNullOrWhiteSpace(Token))
                    throw new Exception("Unable to resolve token for APNS");
    
                var installation = new DeviceInstallation
                {
                    InstallationId = GetDeviceId(),
                    Platform = "apns",
                    PushChannel = Token
                };
    
                installation.Tags.AddRange(tags);
    
                return installation;
            }
    
            string GetNotificationsSupportError()
            {
                if (!NotificationsSupported)
                    return $"This app only supports notifications on iOS {SupportedVersionMajor}.{SupportedVersionMinor} and above. You are running {UIDevice.CurrentDevice.SystemVersion}.";
    
                if (Token == null)
                    return $"This app can support notifications but you must enable this in your settings.";
    
    
                return "An error occurred preventing the use of push notifications";
            }
        }
    }
    

    注意

    このクラスは、一意の ID ( UIDevice.IdentifierForVendor 値を使用) と通知ハブ登録ペイロードを提供します。

  4. Extensions という名前の PushDemo.iOS プロジェクトに新しいフォルダーを追加し、次の実装を使用して NSDataExtensions.cs という名前の空のクラスをそのフォルダーに追加します。

    using System.Text;
    using Foundation;
    
    namespace PushDemo.iOS.Extensions
    {
        internal static class NSDataExtensions
        {
            internal static string ToHexString(this NSData data)
            {
                var bytes = data.ToArray();
    
                if (bytes == null)
                    return null;
    
                StringBuilder sb = new StringBuilder(bytes.Length * 2);
    
                foreach (byte b in bytes)
                    sb.AppendFormat("{0:x2}", b);
    
                return sb.ToString().ToUpperInvariant();
            }
        }
    }
    
  5. AppDelegate.csで、次の名前空間がファイルの先頭に追加されていることを確認します。

    using System;
    using System.Diagnostics;
    using System.Threading.Tasks;
    using Foundation;
    using PushDemo.iOS.Extensions;
    using PushDemo.iOS.Services;
    using PushDemo.Services;
    using UIKit;
    using UserNotifications;
    using Xamarin.Essentials;
    
  6. プライベート プロパティとそれぞれのバッキング フィールドを追加して、 IPushDemoNotificationActionServiceINotificationRegistrationService、および IDeviceInstallationService 実装への参照を格納します。

    IPushDemoNotificationActionService _notificationActionService;
    INotificationRegistrationService _notificationRegistrationService;
    IDeviceInstallationService _deviceInstallationService;
    
    IPushDemoNotificationActionService NotificationActionService
        => _notificationActionService ??
            (_notificationActionService =
            ServiceContainer.Resolve<IPushDemoNotificationActionService>());
    
    INotificationRegistrationService NotificationRegistrationService
        => _notificationRegistrationService ??
            (_notificationRegistrationService =
            ServiceContainer.Resolve<INotificationRegistrationService>());
    
    IDeviceInstallationService DeviceInstallationService
        => _deviceInstallationService ??
            (_deviceInstallationService =
            ServiceContainer.Resolve<IDeviceInstallationService>());
    
  7. RegisterForRemoteNotifications メソッドを追加してユーザー通知設定を登録し、APNS を使用してリモート通知を行います。

    void RegisterForRemoteNotifications()
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            var pushSettings = UIUserNotificationSettings.GetSettingsForTypes(
                UIUserNotificationType.Alert |
                UIUserNotificationType.Badge |
                UIUserNotificationType.Sound,
                new NSSet());
    
            UIApplication.SharedApplication.RegisterUserNotificationSettings(pushSettings);
            UIApplication.SharedApplication.RegisterForRemoteNotifications();
        });
    }
    
  8. CompleteRegistrationAsync メソッドを追加して、プロパティ値を設定しますIDeviceInstallationService.Token。 登録を更新し、最後に保存されてから更新された場合は、デバイス トークンをキャッシュします。

    Task CompleteRegistrationAsync(NSData deviceToken)
    {
        DeviceInstallationService.Token = deviceToken.ToHexString();
        return NotificationRegistrationService.RefreshRegistrationAsync();
    }
    
  9. NSDictionary 通知データを処理し、条件付きで NotificationActionService.TriggerAction を呼び出すための ProcessNotificationActions メソッドを追加します。

    void ProcessNotificationActions(NSDictionary userInfo)
    {
        if (userInfo == null)
            return;
    
        try
        {
            var actionValue = userInfo.ObjectForKey(new NSString("action")) as NSString;
    
            if (!string.IsNullOrWhiteSpace(actionValue?.Description))
                NotificationActionService.TriggerAction(actionValue.Description);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }
    
  10. DeviceToken 引数を CompleteRegistrationAsync メソッドに渡す RegisteredForRemoteNotifications メソッドをオーバーライドします。

    public override void RegisteredForRemoteNotifications(
        UIApplication application,
        NSData deviceToken)
        => CompleteRegistrationAsync(deviceToken).ContinueWith((task)
            => { if (task.IsFaulted) throw task.Exception; });
    
  11. UserInfo 引数を ProcessNotificationActions メソッドに渡す ReceivedRemoteNotification メソッドをオーバーライドします。

    public override void ReceivedRemoteNotification(
        UIApplication application,
        NSDictionary userInfo)
        => ProcessNotificationActions(userInfo);
    
  12. FailedToRegisterForRemoteNotifications メソッドをオーバーライドして、エラーをログに記録します。

    public override void FailedToRegisterForRemoteNotifications(
        UIApplication application,
        NSError error)
        => Debug.WriteLine(error.Description);
    

    注意

    これは非常にプレースホルダーです。 運用環境のシナリオに対して適切なログ記録とエラー処理を実装する必要があります。

  13. IDeviceInstallationService のプラットフォーム固有の実装を渡す呼び出しの直後に を呼び出すように Forms.InitFinishedLaunching メソッドBootstrap.Beginを更新します。

    Bootstrap.Begin(() => new DeviceInstallationService());
    
  14. 同じ方法で、条件付きで承認を要求し、 の直後 Bootstrap.Beginにリモート通知を登録します。

    if (DeviceInstallationService.NotificationsSupported)
    {
        UNUserNotificationCenter.Current.RequestAuthorization(
                UNAuthorizationOptions.Alert |
                UNAuthorizationOptions.Badge |
                UNAuthorizationOptions.Sound,
                (approvalGranted, error) =>
                {
                    if (approvalGranted && error == null)
                        RegisterForRemoteNotifications();
                });
    }
    
  15. 引き続き FinishedLaunching で、options 引数に結果の userInfo オブジェクトをLoadApplication渡す UIApplication.LaunchOptionsRemoteNotificationKey が含まれている場合は、 の呼び出しの直後に ProcessNotificationActions を呼び出します。

    using (var userInfo = options?.ObjectForKey(
        UIApplication.LaunchOptionsRemoteNotificationKey) as NSDictionary)
            ProcessNotificationActions(userInfo);
    

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

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

テスト通知を送信する

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

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

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

    キー
    apikey <your_api_key>
  4. [本文] ののオプションを選択し、形式オプションの一覧から [JSON] を選択し、いくつかのプレースホルダー JSON コンテンツを含めます。

    {
        "text": "Message from Postman!",
        "action": "action_a"
    }
    
  5. ウィンドウの右上にある [保存] ボタンの下にある [コード] ボタンを選択します。 要求は、 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. ターゲット プラットフォーム (Android および iOS) の一方または両方で PushDemo アプリケーションを実行します。

    注意

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

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

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

  9. Postman200 OK 応答が表示され、アラートがアプリに表示され、ActionA アクションが受信されたことを確認します。

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

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

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

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

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

  15. Postman200 OK 応答が返され、アラートがアプリに表示され、ActionA アクションが受信したのではなく、ActionB アクションが受信されたことを確認します。

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

  17. Postman200 OK 応答が返され、サイレント通知が通知領域に表示されないかどうかを検証します。

トラブルシューティング

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

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

Azure API アプリに対してテストする場合は、サービスが実行され、デプロイされ、エラーなしで開始されたチェック。

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

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

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

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

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

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

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

注意

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

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

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

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

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

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

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

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

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

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

状態コードに基づいて、該当する場合は、前のトラブルシューティングの提案を確認してください。

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

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

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

デバイスのエラー メッセージの ID を解決できません

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

次の手順

これで、基本的な Xamarin.Forms アプリがバックエンド サービス経由で通知ハブに接続され、通知を送受信できるようになります。

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

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