- アンドロイド
- コルドバ
- iOS
- ウィンドウズ
- Xamarin.Android
- Xamarin.iOS
- Xamarin.Forms
概要
このチュートリアルでは、 iOS クイック スタート プロジェクトにプッシュ通知を追加して、レコードが挿入されるたびにプッシュ通知がデバイスに送信されるようにします。
ダウンロードしたクイック スタート サーバー プロジェクトを使用しない場合は、プッシュ通知拡張機能パッケージが必要です。 詳細については、「 .NET バックエンド サーバー SDK for Azure Mobile Apps ガイドの操作 」を参照してください。
iOS シミュレーターでは、プッシュ通知はサポートされていません。 物理 iOS デバイスと Apple Developer Program メンバーシップが必要です。
Notification Hub の構成
Azure App Service の Mobile Apps 機能では、Azure Notification Hubs #C1 #B0 を使用してプッシュを送信するため、モバイル アプリの通知ハブを構成します。
Azure ポータルで、アプリ サービスに移動し、アプリのバックエンドを選択します。 [#B0 設定] で、[プッシュ] を選択してください。
アプリに通知ハブリソースを追加するには、接続を選択します。 ハブを作成するか、既存のハブに接続できます。
#B0 #A1 ハブ #A2 #C3 を設定する
これで、通知ハブが Mobile Apps バックエンド プロジェクトに接続されました。 後で、デバイスにプッシュするプラットフォーム通知システム (PNS) に接続するようにこの通知ハブを構成します。
プッシュ通知用にアプリを登録する
- アプリのアプリ ID を登録します。 明示的なアプリ ID (ワイルドカード アプリ ID ではなく) を作成し、 バンドル ID には Xcode クイック スタート プロジェクトにある正確なバンドル ID を使用します。 また、[ プッシュ通知 ] オプションを選択することも重要です。
- 次 に、プッシュ通知の構成を準備するには、"開発" または "配布" SSL 証明書を作成します。
プッシュ通知を送信するように Azure を構成する
- Mac で、 キーチェーン アクセスを起動します。 左側のナビゲーション バーの [ カテゴリ] で、[ 個人用証明書] を開きます。 前のセクションでダウンロードした SSL 証明書を見つけて、その内容を開示します。 証明書のみを選択します (秘密キーは選択しないでください)。 次にエクスポートします。
- Azure portal で、すべてを参照>App Services を選択します。 次に、Mobile Apps バックエンドを選択します。
- 設定でApp Service プッシュを選択します。 次に、通知ハブ名を選択します。
- Apple Push Notification Services>Upload Certificate に移動します。 正しい モード を選択して 、.p12 ファイルをアップロードします (以前のクライアント SSL 証明書が運用環境かサンドボックスかに応じて異なります)。 変更を保存します。
これで、iOS でプッシュ通知を操作するようにサービスが構成されました。
プッシュ通知を送信するようにバックエンドを更新する
.NET バックエンド (C#):
Visual Studio で、サーバー プロジェクトを右クリックし、[ NuGet パッケージの管理] をクリックし、
Microsoft.Azure.NotificationHubs
を検索して、[ インストール] をクリックします。 これにより、バックエンドから通知を送信するための Notification Hubs ライブラリがインストールされます。バックエンドの Visual Studio プロジェクトで、 Controllers>TodoItemController.cs を開きます。 ファイルの先頭に、次の
using
ステートメントを追加します。using Microsoft.Azure.Mobile.Server.Config; using Microsoft.Azure.NotificationHubs;
PostTodoItem
メソッドを次のコードに置き換えます。public async Task<IHttpActionResult> PostTodoItem(TodoItem item) { TodoItem current = await InsertAsync(item); // Get the settings for the server project. HttpConfiguration config = this.Configuration; MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); // Get the Notification Hubs credentials for the Mobile App. string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; // Create a new Notification Hub client. NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName); // iOS payload var appleNotificationPayload = "{\"aps\":{\"alert\":\"" + item.Text + "\"}}"; try { // Send the push notification and log the results. var result = await hub.SendAppleNativeNotificationAsync(appleNotificationPayload); // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); } return CreatedAtRoute("Tables", new { id = current.Id }, current); }
サーバープロジェクトを再公開します。
バックエンドNode.js:
バックエンド プロジェクトを設定します。
todoitem.js テーブル スクリプトを次のコードに置き換えます。
var azureMobileApps = require('azure-mobile-apps'), promises = require('azure-mobile-apps/src/utilities/promises'), logger = require('azure-mobile-apps/src/logger'); var table = azureMobileApps.table(); // When adding record, send a push notification via APNS table.insert(function (context) { // For details of the Notification Hubs JavaScript SDK, // see https://aka.ms/nodejshubs logger.info('Running TodoItem.insert'); // Create a payload that contains the new item Text. var payload = "{\"aps\":{\"alert\":\"" + context.item.text + "\"}}"; // Execute the insert; Push as a post-execute action when results are returned as a Promise. return context.execute() .then(function (results) { // Only do the push if configured if (context.push) { context.push.apns.send(null, payload, function (error) { if (error) { logger.error('Error while sending push notification: ', error); } else { logger.info('Push notification sent successfully!'); } }); } return results; }) .catch(function (error) { logger.error('Error while running context.execute: ', error); }); }); module.exports = table;
ローカル コンピューターでファイルを編集するときは、サーバー プロジェクトを再発行します。
アプリにプッシュ通知を追加する
Objective-C:
QSAppDelegate.m で、iOS SDK と QSTodoService.h をインポートします。
#import <MicrosoftAzureMobile/MicrosoftAzureMobile.h> #import "QSTodoService.h"
QSAppDelegate.m の
didFinishLaunchingWithOptions
で、return YES;
の直前に次の行を挿入します。UIUserNotificationSettings* notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings]; [[UIApplication sharedApplication] registerForRemoteNotifications];
QSAppDelegate.m で、次のハンドラー メソッドを追加します。 これで、プッシュ通知をサポートするようにアプリが更新されました。
// Registration with APNs is successful - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { QSTodoService *todoService = [QSTodoService defaultService]; MSClient *client = todoService.client; [client.push registerDeviceToken:deviceToken completion:^(NSError *error) { if (error != nil) { NSLog(@"Error registering for notifications: %@", error); } }]; } // Handle any failure to register - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError: (NSError *)error { NSLog(@"Failed to register for remote notifications: %@", error); } // Use userInfo in the payload to display an alert. - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { NSLog(@"%@", userInfo); NSDictionary *apsPayload = userInfo[@"aps"]; NSString *alertString = apsPayload[@"alert"]; // Create alert with notification content. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Notification" message:alertString preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { NSLog(@"Cancel"); }]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", @"OK") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { NSLog(@"OK"); }]; [alertController addAction:cancelAction]; [alertController addAction:okAction]; // Get current view controller. UIViewController *currentViewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; while (currentViewController.presentedViewController) { currentViewController = currentViewController.presentedViewController; } // Display alert. [currentViewController presentViewController:alertController animated:YES completion:nil]; }
Swift:
次の内容を含む ClientManager.swift ファイルを追加します。 %AppUrl% を Azure Mobile App バックエンドの URL に置き換えます。
class ClientManager { static let sharedClient = MSClient(applicationURLString: "%AppUrl%") }
ToDoTableViewController.swift で、
MSClient
を初期化するlet client
行を次の行に置き換えます。let client = ClientManager.sharedClient
AppDelegate.swift で、
func application
の本文を次のように置き換えます。func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.registerUserNotificationSettings( UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)) application.registerForRemoteNotifications() return true }
AppDelegate.swift で、次のハンドラー メソッドを追加します。 これで、プッシュ通知をサポートするようにアプリが更新されました。
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { ClientManager.sharedClient.push?.registerDeviceToken(deviceToken) { error in print("Error registering for notifications: ", error?.description) } } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { print("Failed to register for remote notifications: ", error.description) } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject: AnyObject]) { print(userInfo) let apsNotification = userInfo["aps"] as? NSDictionary let apsString = apsNotification?["alert"] as? String let alert = UIAlertController(title: "Alert", message: apsString, preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default) { _ in print("OK") } let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { _ in print("Cancel") } alert.addAction(okAction) alert.addAction(cancelAction) var currentViewController = self.window?.rootViewController while currentViewController?.presentedViewController != nil { currentViewController = currentViewController?.presentedViewController } currentViewController?.presentViewController(alert, animated: true) {} }
プッシュ通知をテストする
- Xcode で、[ 実行 ] を押し、iOS デバイスでアプリを起動します (プッシュはシミュレーターでは機能しないことに注意してください)。 [ OK] を クリックしてプッシュ通知を受け入れます。この要求は、アプリを初めて実行したときに発生します。
- アプリで新しい項目を追加し、[ +] をクリックします。
- 通知が受信されたことを確認し、[ OK] をクリックして通知を閉じます。 これで、このチュートリアルは正常に完了しました。
もっと
- テンプレートを使用すると、クロスプラットフォーム プッシュとローカライズされたプッシュを柔軟に送信できます。 Azure Mobile Apps で iOS クライアント ライブラリを使用する方法 については、テンプレートを登録する方法を示します。