Apple プラットフォーム アプリでメッセージを受信する

プラットフォームを選択: iOS+ Android Web Flutter Unity C++


クライアント アプリがデバイスにインストールされると、アプリは FCM APNs インターフェースを通じてメッセージを受信できます。Notifications Composer を使用してユーザー セグメントに通知をすぐに送信したり、アプリケーション サーバーでメッセージを作成したりできます。

アラート通知を処理する

FCM では、Apple アプリをターゲットにしたすべてのメッセージを APNs を通じて配信します。UNUserNotificationCenter を使用した APNs 通知の受信の詳細については、Apple のドキュメントの Handling Notifications and Notification-Related Actionss をご覧ください。

FCM からディスプレイ通知を受信するためには、UNUserNotificationCenter delegate を設定して、適切なデリゲート メソッドを実装する必要があります。

Swift

// Receive displayed notifications for iOS 10+ devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification) async
  -> UNNotificationPresentationOptions {
  let userInfo = notification.request.content.userInfo

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // Messaging.messaging().appDidReceiveMessage(userInfo)

  // ...

  // Print full message.
  print(userInfo)

  // Change this to your preferred presentation option
  // Note: UNNotificationPresentationOptions.alert has been deprecated.
  return [.list, .banner, .sound]
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse) async {
  let userInfo = response.notification.request.content.userInfo

  // ...

  // Print full message.
  print(userInfo)
}

Objective-C

// Receive displayed notifications for iOS 10+ devices.
// Handle incoming notification messages while app is in the foreground.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  NSDictionary *userInfo = notification.request.content.userInfo;

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Print full message.
  NSLog(@"%@", userInfo);

  // Change this to your preferred presentation option
  completionHandler(UNNotificationPresentationOptionList |
                    UNNotificationPresentationOptionBanner |
                    UNNotificationPresentationOptionSound);
}

- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken {
    NSLog(@"FCM registration token: %@", fcmToken);
    // Notify about received token.
    NSDictionary *dataDict = [NSDictionary dictionaryWithObject:fcmToken forKey:@"token"];
    [[NSNotificationCenter defaultCenter] postNotificationName:
     @"FCMToken" object:nil userInfo:dataDict];
    // TODO: If necessary send token to application server.
    // Note: This callback is fired at each app startup and whenever a new token is generated.
}

- (void)logFCMToken {
  NSString *fcmToken = [FIRMessaging messaging].FCMToken;
  NSLog(@"Local FCM registration token: %@", fcmToken);

  NSString* displayToken = [NSString stringWithFormat:@"Logged FCM token: %@", fcmToken];

  [[FIRMessaging messaging] tokenWithCompletion:^(NSString * _Nullable token, NSError * _Nullable error) {
    if (error != nil) {
      NSLog(@"Error fetching the remote FCM registration token: %@", error);
    } else {
      NSLog(@"Remote FCM registration token: %@", token);
      NSString* message =
        [NSString stringWithFormat:@"FCM registration token: %@", token];
      // display message
      NSLog(@"%@", message);
    }
  }];
  NSLog(@"%@", displayToken);
}

- (void)subsribeToTopic {
  [[FIRMessaging messaging] subscribeToTopic:@"weather"
                                  completion:^(NSError * _Nullable error) {
    NSLog(@"Subscribed to weather topic");
  }];
}

@end

通知にカスタム アクションを追加するには、通知ペイロードclick_action パラメータを設定します。この値は、APNs ペイロードの category キーに使うものと同じ値を使用します。カスタム アクションを使用するには、まず登録する必要があります。詳細については、Apple の Local and Remote Notification Programming Guide をご覧ください。

アプリへのメッセージ配信については、FCM レポート ダッシュボードをご覧ください。このダッシュボードには、Android アプリの「インプレッション」(ユーザーが表示した通知)のデータとともに、Apple と Android のデバイスで送信および開封されたメッセージの数が記録されています。

サイレント プッシュ通知を処理する

content-available キーを使ってメッセージを送信する場合(APNs の content-available に相当)、メッセージはサイレント通知として配信され、バックグラウンドでのデータ更新などのタスクを行うために、アプリがバックグラウンドで起動します。フォアグラウンド通知とは異なり、これらの通知は application(_:didReceiveRemoteNotification:fetchCompletionHandler:) メソッドで処理する必要があります。

次のように application(_:didReceiveRemoteNotification:fetchCompletionHandler:) を実装します。

Swift

@MainActor
func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async
  -> UIBackgroundFetchResult {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // Messaging.messaging().appDidReceiveMessage(userInfo)

  // ...

  // Print full message.
  print(userInfo)
  print("Call exportDeliveryMetricsToBigQuery() from AppDelegate")
  Messaging.serviceExtension().exportDeliveryMetricsToBigQuery(withMessageInfo: userInfo)
  return UIBackgroundFetchResult.newData
}

Objective-C

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired until the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler(UIBackgroundFetchResultNewData);
}

Apple プラットフォームでは、バックグラウンド通知の配信が保証されるわけではありません。バックグラウンド通知が失敗する原因となる条件については、Apple のドキュメントの Pushing Background Updates to Your App をご覧ください。

通知メッセージ ペイロードを解釈する

通知メッセージのペイロードは、キーと値の辞書です。APNs 経由で送信される通知メッセージは、次のような APNs ペイロード形式になります。

  {
    "aps" : {
      "alert" : {
        "body" : "great match!",
        "title" : "Portugal vs. Denmark",
      },
      "badge" : 1,
    },
    "customKey" : "customValue"
  }

メソッドの実装入れ替えが無効にされたメッセージを処理する

デフォルトでは、アプリのデリゲート クラスを UNUserNotificationCenterMessaging のデリゲート プロパティに割り当てると、FCM はアプリ デリゲート クラスを入れ替えて、FCM トークンをデバイスの APNs トークンに自動的に関連付け、通知受信イベントをAnalyticsに渡します。メソッドの実装入れ替えを明示的に無効にする場合、SwiftUI アプリを構築している場合、またはいずれかのデリゲートに別のクラスを使用する場合は、これらのタスクを手動で行う必要があります。

FCM トークンをデバイスの APNs トークンに関連付けるには、アプリ デリゲートのトークン更新ハンドラ内で、apnsToken プロパティを使用して APNs トークンを Messaging クラスに渡します。

Swift

func application(_ application: UIApplication,
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  Messaging.messaging().apnsToken = deviceToken;
}

Objective-C

- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  [FIRMessaging messaging].APNSToken = deviceToken;
}

通知の受信情報を Analytics に渡すには、appDidReceiveMessage(_:) メソッドを使用します。

Swift

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
  withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
  let userInfo = notification.request.content.userInfo

  Messaging.messaging().appDidReceiveMessage(userInfo)

  // Change this to your preferred presentation option
  completionHandler([[.alert, .sound]])
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {
  let userInfo = response.notification.request.content.userInfo

  Messaging.messaging().appDidReceiveMessage(userInfo)

  completionHandler()
}

func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable : Any],
  fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  Messaging.messaging().appDidReceiveMessage(userInfo)
  completionHandler(.noData)
}

Objective-C

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
      willPresentNotification:(UNNotification *)notification
        withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  NSDictionary *userInfo = notification.request.content.userInfo;

  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Change this to your preferred presentation option
  completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
        withCompletionHandler:(void(^)(void))completionHandler {
  NSDictionary *userInfo = response.notification.request.content.userInfo;

  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  completionHandler();
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
  [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
  completionHandler(UIBackgroundFetchResultNoData);
}