LoginSignup
1
0

More than 3 years have passed since last update.

Azure Notification Hubを使ってC#でiOSアプリにプッシュ通知を送信

Posted at

はじめに

Azure Notification Hubを使ってC#でiOSアプリにタグ指定でプッシュ通知を送信するメモ。
Azure Notification Hubを使うと、任意のデバイスに任意のタグ指定(スマホアプリ側で指定した任意の文字列)で
送信することができるので実装が楽。

環境

・Azure Notification Hub
・Windows 10 Pro
・C#(Visual Studio 2019)
・.NET Core 2.1
・コンソールアプリケーション
・使用したデバイス iPad Air

事前準備

1.Azure Notification Hubの構築
APNSの設定等あるので詳細はMicrosoftのドキュメントをご確認ください。
  
作成時に以下の情報をメモ
・Notification Hubの名前
  -> Overview/Name
    
・Notification Hubの接続文字列
  -> Manage/Access Policiesの送信権限が付与されているPolicyのConnection String
   (デフォルトだと:DefaultFullSharedAccessSignatureのほう)

2.スマホにテスト用アプリをインストール
・接続時に指定したTagをメモ

3.NuGetで使用するパッケージをインストール

Visual Studioでプロジェクトを開き
NuGetパッケージマネージャで以下のパッケージを検索しインストール
  
・Microsoft.Azure.NotificationHubs(作成者:Microsoft)

実装

Program.cs
using Microsoft.Azure.NotificationHubs;
using System;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "Azureに作成したNotificationHubのConnection String";
            string hubName = "送信対象のハブ名";
            string payload = @"{""aps"":{""alert"":""test""}}";
            string tag = "送信対象のタグ";

            // クライアントを作成 
            var client = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);

            // iOSにタグ指定でJsonデータを送信
            var task = client.SendAppleNativeNotificationAsync(payload, tag);

            // AndroidもSendFcmNativeNotificationAsyncを使うことで簡単にできそうだが未確認

            // ~以下略~
        }
    }
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0