在 iOS 应用中接收消息

您的客户端应用在安装到设备上后,就可以通过 FCM APNs 接口接收消息。您可以使用通知编辑器立即开始向细分用户群发送通知,或者您的应用服务器可以通过 APNs 接口发送带有通知有效负载的消息。

在大多数典型的使用情形中,都可能需要处理通过 FCM APNs 接口接收的消息。您还可以发送上行消息,或在前台应用中接收数据消息

处理通过 FCM APNs 接口接收到的消息

当您的应用处于后台时,iOS 会将含有 notification 键的消息发送到系统托盘。用户点按一条通知即可打开该应用,系统会将通知的内容传递给 AppDelegate 中的 didReceiveRemoteNotification 回调函数。

按如下所示实现 AppDelegate application:didReceiveRemoteNotification:

Swift

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  // 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 message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
  // 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 message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)

  completionHandler(UIBackgroundFetchResult.newData)
}

Objective-C

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
  // 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
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Print message ID.
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }

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

- (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 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
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // Print message ID.
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }

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

  completionHandler(UIBackgroundFetchResultNewData);
}

如果您希望打开应用并执行某项特定操作,请在通知有效负载中设置 click_action。使用的值应与您将在 APNs 有效负载的 category 键中使用的值相同。

解读通知消息有效负载

通知消息的有效负载是由键和值组成的字典。通过 APNs 发送的通知消息需要遵循如下 APNs 有效负载格式:

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

处理前台应用中的数据消息

要在应用于前台运行时直接从 FCM(而不是通过 APNs)接收仅包含数据的消息,您需要连接到 FCM 服务并使用 FIRMessagingDelegatemessaging:didReceiveMessage: 处理消息。

要进行连接,请在 AppDelegate 中将 shouldEstablishDirectChannel 标志设为 YES。FCM 会管理连接,在您的应用转到后台时断开连接,并在应用每次返回前台时重新建立连接。

要在应用于前台运行时接收数据消息,请实现 messaging:didReceiveMessage:。当您的应用在后台运行时,即使没有此回调函数,应用仍然可以接收数据消息;但当应用处于前台时,您就需要处理此回调函数。

在方法调配已停用的情况下处理消息

如果您停用了方法调配,则需要调用一个方法来让 FCM 跟踪消息传递和分析过程。如果启用了方法调配则会自动执行这一跟踪操作。

从 iOS 10 开始,您可以设置 UNUserNotificationCenter delegate 以接收来自 Apple 的显示通知,还可以设置 FIRMessaging remoteMessageDelegate 以接收来自 FCM 的数据消息。如果不使用 AppDelegate 设置这两个委托,则用于消息处理的方法调配会被停用。您需要调用 appDidReceiveMessage: 方法才能跟踪消息传递和分析过程。

Objective-C:iOS 10

// 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 message ID.
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }

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

  // Change this to your preferred presentation option
  completionHandler(UNNotificationPresentationOptionNone);
}

// Handle notification messages after display notification is tapped by the user.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void(^)(void))completionHandler {
  NSDictionary *userInfo = response.notification.request.content.userInfo;
  if (userInfo[kGCMMessageIDKey]) {
    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
  }

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

  completionHandler();
}

Objective-C:iOS 9

// With "FirebaseAppDelegateProxyEnabled": NO
   - (void)application:(UIApplication *)application
     didReceiveRemoteNotification:(NSDictionary *)userInfo
           fetchCompletionHandler:
               (void (^)(UIBackgroundFetchResult))completionHandler {
   // Let FCM know about the message for analytics etc.
   [[FIRMessaging messaging] appDidReceiveMessage:userInfo];
   // handle your message.
 }
 

Swift:iOS 10

@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {

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

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

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
  }

  func userNotificationCenter(_ center: UNUserNotificationCenter,
                              didReceive response: UNNotificationResponse,
                              withCompletionHandler completionHandler: @escaping () -> Void) {
    let userInfo = response.notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
      print("Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    completionHandler()
  }
}

Swift:iOS 9

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
     // Let FCM know about the message for analytics etc.
     FIRMessaging.messaging().appDidReceiveMessage(userInfo)
     // handle your message
   }
 

解读数据消息有效负载

数据消息的有效负载是由键和值组成的字典。由 FCM 服务器直接发送到设备的数据消息采用如下所示的字典格式:

  {
    "body" : "great match!",
    "title" : "Portugal vs. Denmark",
    "icon" : "myicon"
  }

处理已加入队列和已删除的消息

连接到 FCM 接收数据消息的应用应处理 FIRMessagingMessagesDeletedNotification。如果您在特定设备上的应用在该设备连接 FCM 时有过多的待处理消息(超过 100 条),或者该设备超过一个月未连接到 FCM,则您可能会收到此回调。当应用实例收到此回调时,应与您的应用服务器完全同步一次。

发送以下问题的反馈:

此网页
需要帮助?请访问我们的支持页面