Skip to content

プッシュ通知の統合

このリファレンス記事では、Braze Swift SDK の iOS プッシュ通知を設定する方法について説明します。

プッシュ通知を使用する と、重要なイベントが発生したときにアプリから通知を送信できます。新しいインスタントメッセージを配信したり、ニュース速報を送信したり、ユーザーのお気に入りのテレビ番組の最新エピソードがダウンロードしてオフライン視聴する準備ができたときに、プッシュ通知を送信することがあります。プッシュ通知は サイレントにすることもでき、アプリのインターフェースを更新したり、バックグラウンド作業をトリガーしたりするためにのみ使用されます。

プッシュ通知は、バックグラウンドでの取得間の遅延が許容できないような、散発的だが即時に必要なコンテンツに適しています。プッシュ通知は、アプリケーションが必要な場合にのみ起動するため、バックグラウンドでの取得よりもはるかに効率的です。

プッシュ通知にはレート制限があるため、アプリケーションで必要な数だけ送信しても問題ありません。iOS と Apple Push Notification サービス (APNs) サーバーが通知の配信頻度を制御するため、送信しすぎても問題が発生することはありません。プッシュ通知がスロットリングされている場合、デバイスが次にキープアライブパケットを送信するか、別の通知を受信するまで遅延する可能性があります。

前提条件

プッシュ通知証明書

Braze を使用して iOS のプッシュ通知を送信する前に、Apple が提供する .p8 のプッシュ通知ファイルを用意する必要があります。Apple の開発者向けドキュメントに記載されているように、

  1. Apple 開発者アカウントで、[証明書、識別子 & プロファイル] を開きます。
  2. [キー] で [すべて] を選択し、右上の追加ボタン (+) をクリックします。
  3. [キーの説明]で、署名キーの一意の名前を入力します。
  4. [キーサービス] で [Apple プッシュ通知サービス (APNs)] チェックボックスをオンにし、[続行] をクリックします。[確認] をクリックします。
  5. キー ID をメモしておきます。[ダウンロード] をクリックして、キーを生成してダウンロードします。ダウンロードしたファイルは、何度もダウンロードできませんので、安全な場所に保存してください。
  6. Braze で、[設定] > [アプリ設定] に移動し、[Apple プッシュ通知証明書] で .p8 ファイルをアップロードします。開発用または実稼働用のプッシュ証明書のいずれかをアップロードできます。アプリが App Store で公開された後にプッシュ通知をテストするには、アプリの開発バージョン用に別のワークスペースを設定することをお勧めします。
  7. プロンプトが表示されたら、アプリのバンドル IDキー IDチーム IDを入力し、[保存] をクリックします。

プッシュ機能を有効にする

Xcode で、[署名と機能] ペインを使用して、プッシュ通知機能をメイン アプリ ターゲットに追加します。

自動プッシュ統合

Swift SDK は、Braze から受信したリモート通知の処理を自動化するための構成のみのアプローチを提供します。このアプローチはプッシュ通知を統合する最も簡単な方法であり、ほとんどのお客様に推奨されます。

自動プッシュ統合を有効にするには、 automation の財産 push 構成 true:

1
2
let configuration = Braze.Configuration(apiKey: "{YOUR-BRAZE-API-KEY}", endpoint: "{YOUR-BRAZE-API-ENDPOINT}")
configuration.push.automation = true
1
2
BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:@"{YOUR-BRAZE-API-KEY}" endpoint:@"{YOUR-BRAZE-API-ENDPOINT}"];
configuration.push.automation = [[BRZConfigurationPushAutomation alloc] initEnablingAllAutomations:YES];

これにより、SDK に次の指示が与えられます。 - システムにプッシュ通知用のアプリケーションを登録します。 - 初期化時にプッシュ通知の承認/許可を要求します。 - プッシュ通知関連のシステムデリゲートメソッドの実装を動的に提供します。

個々の設定を上書きする

よりきめ細かな制御を行うために、各自動化ステップを個別に有効または無効にすることができます。

1
2
3
// Enable all automations and disable the automatic notification authorization request at launch.
configuration.push.automation = true
configuration.push.automation.requestAuthorizationAtLaunch = false
1
2
3
// Enable all automations and disable the automatic notification authorization request at launch.
configuration.push.automation = [[BRZConfigurationPushAutomation alloc] initEnablingAllAutomations:YES];
configuration.push.automation.requestAuthorizationAtLaunch = NO;

見る Braze.Configuration.Push.Automation 利用可能なすべてのオプションと automation 自動化の動作の詳細については、こちらをご覧ください。

自動プッシュ統合を使用している場合は、次のセクションをスキップして ディープリンク に進むことができます。

手動プッシュ統合

プッシュ通知は手動で統合することもできます。このセクションでは、この統合に必要な手順について説明します。

ステップ 1:APNsでプッシュ通知を登録する

アプリ内に適切なコードサンプルを含めてください application:didFinishLaunchingWithOptions: ユーザーのデバイスが APNs に登録できるように、デリゲート メソッドを使用します。アプリケーションのメインスレッドですべてのプッシュ統合コードを呼び出すようにしてください。

Braze には、プッシュアクションボタンをサポートするデフォルトのプッシュカテゴリーも用意されており、プッシュ登録コードに手動で追加する必要があります。その他の統合手順については プッシュアクションボタン を参照してください。

次のコードを application:didFinishLaunchingWithOptions: アプリデリゲートのメソッド。

1
2
3
4
5
6
7
8
9
10
11
application.registerForRemoteNotifications()
let center = UNUserNotificationCenter.current()
center.setNotificationCategories(Braze.Notifications.categories)
center.delegate = self
var options: UNAuthorizationOptions = [.alert, .sound, .badge]
if #available(iOS 12.0, *) {
  options = UNAuthorizationOptions(rawValue: options.rawValue | UNAuthorizationOptions.provisional.rawValue)
}
center.requestAuthorization(options: options) { granted, error in
  print("Notification authorization, granted: \(granted), error: \(String(describing: error))")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[application registerForRemoteNotifications];
UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter;
[center setNotificationCategories:BRZNotifications.categories];
center.delegate = self;
UNAuthorizationOptions options = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
if (@available(iOS 12.0, *)) {
  options = options | UNAuthorizationOptionProvisional;
}
[center requestAuthorizationWithOptions:options
                      completionHandler:^(BOOL granted, NSError *_Nullable error) {
                        NSLog(@"Notification authorization, granted: %d, "
                              @"error: %@)",
                              granted, error);
}];

ステップ 2: Braze にプッシュトークンを登録する

APNs登録が完了したら、結果を渡します deviceToken Braze にプッシュ通知を有効にしてユーザーに送信します。

アプリの application(_:didRegisterForRemoteNotificationsWithDeviceToken:) メソッドに次のコードを追加します。

1
AppDelegate.braze?.notifications.register(deviceToken: deviceToken)

アプリの application:didRegisterForRemoteNotificationsWithDeviceToken: メソッドに次のコードを追加します。

1
[AppDelegate.braze.notifications registerDeviceToken:deviceToken];

ステップ 3: プッシュ処理を有効にする

次に、受信したプッシュ通知を Braze に渡します。この手順は、プッシュ分析とリンク処理をログに記録するために必要です。アプリケーションのメインスレッドですべてのプッシュ統合コードを呼び出すようにしてください。

アプリの application(_:didReceiveRemoteNotification:fetchCompletionHandler:) メソッドに次のコードを追加します。

1
2
3
4
5
6
7
if let braze = AppDelegate.braze, braze.notifications.handleBackgroundNotification(
  userInfo: userInfo,
  fetchCompletionHandler: completionHandler
) {
  return
}
completionHandler(.noData)

次に、アプリの userNotificationCenter(_:didReceive:withCompletionHandler:) メソッドに次のコードを追加します。

1
2
3
4
5
6
7
if let braze = AppDelegate.braze, braze.notifications.handleUserNotification(
  response: response,
  withCompletionHandler: completionHandler
) {
  return
}
completionHandler()

フォアグラウンドでのプッシュ通知処理

アプリがフォアグラウンドにある間にプッシュ通知を表示するには、userNotificationCenter(_:willPresent:withCompletionHandler:) を実装します。

1
2
3
4
5
6
7
8
9
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  if #available(iOS 14.0, *) {
    completionHandler([.list, .banner])
  } else {
    completionHandler([.alert])
  }
}

フォアグラウンド通知がクリックされると、iOS 10のプッシュデリゲート userNotificationCenter(_:didReceive:withCompletionHandler:) が呼び出され、Braze はプッシュクリックイベントをログに記録します。

アプリケーションの application:didReceiveRemoteNotification:fetchCompletionHandler: メソッドに次のコードを追加します。

```objc BOOL processedByBraze = AppDelegate.braze != nil && [AppDelegate.braze.notifications handleBackgroundNotificationWithUserInfo:userInfo fetchCompletionHandler:completionHandler]; if (processedByBraze) { return ()

completionHandler(UIBackgroundFetchResultNoData); ```

次に、アプリの (void)userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: メソッドに次のコードを追加します。

```objc BOOL processedByBraze = AppDelegate.braze != nil && [AppDelegate.braze.notifications handleUserNotificationWithResponse:response withCompletionHandler:completionHandler]; if (processedByBraze) { return ()

completionHandler(); ```

フォアグラウンドでのプッシュ通知処理

アプリがフォアグラウンドにある間にプッシュ通知を表示するには、userNotificationCenter:willPresentNotification:withCompletionHandler: を実装します。

1
2
3
4
5
6
7
8
9
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
  if (@available(iOS 14.0, *)) {
    completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner);
  } else {
    completionHandler(UNNotificationPresentationOptionAlert);
  }
}

フォアグラウンド通知がクリックされると、iOS 10のプッシュデリゲート userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: が呼び出され、Braze はプッシュクリックイベントをログに記録します。

ディープリンク

プッシュからアプリへのディープリンクは、標準のプッシュ統合ドキュメントを介して自動的に処理されます。アプリ内の特定の場所にディープリンクを追加する方法について詳しくは、高度なユースケースを参照してください。

プッシュ通知の更新を購読する

Brazeによって処理されたプッシュ通知ペイロードにアクセスするには、 Braze.Notifications.subscribeToUpdates(_:) 方法。

1
2
3
4
5
6
// This subscription is maintained through a Braze cancellable, which will observe for changes until the subscription is cancelled.
// You must keep a strong reference to the cancellable to keep the subscription active.
// The subscription is canceled either when the cancellable is deinitialized or when you call its `.cancel()` method.
let cancellable = AppDelegate.braze?.notifications.subscribeToUpdates { payload in
  print("Braze processed notification with title '\(payload.title)' and body '\(payload.body)'")
}
1
2
3
BRZCancellable *cancellable = [notifications subscribeToUpdatesWithInternalNotifications:NO update:^(BRZNotificationsPayload * _Nonnull payload) {
  NSLog(@"Braze processed notification with title '%@' and body '%@'", payload.title, payload.body);
}];

{#push-testing} のテスト

コマンドラインからアプリ内通知とプッシュ通知をテストする場合は、CURL と メッセージング API を介してターミナルから単一の通知を送信できます。次のフィールドをテストケースの正しい値に置き換える必要があります。

  • YOUR_API_KEY - [設定] > [API キー] で利用できます。
  • YOUR_EXTERNAL_USER_ID - [ユーザーの検索] ページで使用できます。詳細については、ユーザーIDの割り当てを参照してください。
  • YOUR_KEY1 (省略可能)
  • YOUR_VALUE1 (省略可能)
1
2
3
4
5
6
7
8
9
10
11
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer {YOUR_API_KEY}" -d '{
  "external_user_ids":["YOUR_EXTERNAL_USER_ID"],
  "messages": {
    "apple_push": {
      "alert":"Test push",
      "extra": {
        "YOUR_KEY1":"YOUR_VALUE1"
      }
    }
  }
}' https://rest.iad-01.braze.com/messages/send

上記の例は、 US-01 実例。このインスタンスにいない場合は、API ドキュメントを参照して、どのエンドポイントにリクエストを送信するかを確認してください。

プッシュプライマー

プッシュプライマーキャンペーンでは、アプリのデバイスでプッシュ通知を有効にするようにユーザーに促します。これは、ノーコードプッシュプライマーを使用して、SDK のカスタマイズなしで行うことができます。

「このページはどの程度役に立ちましたか?」
New Stuff!