Send Messages to Multiple Devices

Firebase Cloud Messaging provides two ways to target a message to multiple devices:

  • Topic messaging, which allows you to send a message to multiple devices that have opted in to a particular topic.
  • Device group messaging, which allows you to send a single message to multiple instance of an app running on devices belonging to a group.

This tutorial focuses on sending topic messages from your app server using the HTTP or XMPP protocols for FCM, and receiving and handling them in an iOS app. This page lists all the steps to achieve this, from setup to verification — so it may cover steps you already completed if you have set up an iOS client app for FCM or worked through the steps to Send your First Message.

Add Firebase to your iOS project

This section covers tasks you may have completed if you have already enabled other Firebase features for your app. For Notifications specifically, you'll need to upload your APNs certificate and register for remote notifications.

Prerequisites

Before you begin, you need a few things set up in your environment:

  • Xcode 7.0 or later
  • An Xcode project targeting iOS 7 or above
  • The bundle identifier of your app
  • CocoaPods 1.0.0 or later
  • For Cloud Messaging:
    • A physical iOS device
    • APNs certificate with Push Notifications enabled
    • In Xcode, enable Push Notifications in App > Capabilities

If you don't have an Xcode project already, you can download one of our quickstart samples if you just want to try a Firebase feature. If you're using a quickstart, remember to get the bundle identifier from the project settings, you'll need it for the next step.

Add Firebase to your app

It's time to add Firebase to your app. To do this you'll need a Firebase project and a Firebase configuration file for your app.

  1. Create a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.
  2. Click Add Firebase to your iOS app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
  3. When prompted, enter your app's bundle ID. It's important to enter the bundle ID your app is using; this can only be set when you add an app to your Firebase project.
  4. At the end, you'll download a GoogleService-Info.plist file. You can download this file again at any time.
  5. If you haven't done so already, copy this into your Xcode project root.

Add the SDK

If you are setting up a new project, you need to install the SDK. You may have already completed this as part of creating a Firebase project.

We recommend using CocoaPods to install the libraries. You can install Cocoapods by following the installation instructions. If you'd rather not use CocoaPods, you can integrate the SDK frameworks directly by following the instructions below.

If you are planning to download and run one of the quickstart samples, the Xcode project and Podfile are already present, but you'll still need to install the pods and download the GoogleService-Info.plist file. If you would like to integrate the Firebase libraries into one of your own projects, you will need to add the pods for the libraries that you want to use.

  1. If you don't have an Xcode project yet, create one now.

  2. Create a Podfile if you don't have one:

    $ cd your-project directory
    $ pod init
    
  3. Add the pods that you want to install. You can include a Pod in your Podfile like this:

    pod 'Firebase/Core'
    pod 'Firebase/Messaging'
    

    This will add the prerequisite libraries needed to get Firebase up and running in your iOS app, along with Firebase Analytics. A list of currently available pods and subspecs is provided below. These are linked in feature specific setup guides as well.

  4. Install the pods and open the .xcworkspace file to see the project in Xcode.

    $ pod install
    $ open your-project.xcworkspace
    
  5. Download a GoogleService-Info.plist file from Firebase console and include it in your app.

Upload your APNs certificate

Upload your APNs certificate to Firebase. If you don't already have an APNs certificate, see Provisioning APNs SSL Certificates.

  1. Inside your project in the Firebase console, select the gear icon, select Project Settings, and then select the Cloud Messaging tab.

  2. Select the Upload Certificate button for your development certificate, your production certificate, or both. At least one is required.

  3. For each certificate, select the .p12 file, and provide the password, if any. Make sure the bundle ID for this certificate matches the bundle ID of your app. Select Save.

Initialize Firebase in your app

You'll need to add Firebase initialization code to your application. Import the Firebase module and configure a shared instance as shown:

  1. Import the Firebase module in your UIApplicationDelegate subclass:

    Swift

    import Firebase
    

    Objective-C

    @import Firebase;
    
  2. Configure a FIRApp shared instance, typically in your application's application:didFinishLaunchingWithOptions: method:

    Swift

    // Use Firebase library to configure APIs
    FIRApp.configure()
    

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
    

Register for remote notifications

Either at startup, or at the desired point in your application flow, register your app for remote notifications. Call registerForRemoteNotifications as shown:

Objective-C

if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
  UIUserNotificationType allNotificationTypes =
  (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
  UIUserNotificationSettings *settings =
  [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
  [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
} else {
  // iOS 10 or later
  #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  // For iOS 10 display notification (sent via APNS)
  [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  UNAuthorizationOptions authOptions =
      UNAuthorizationOptionAlert
      | UNAuthorizationOptionSound
      | UNAuthorizationOptionBadge;
  [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
      }];

  // For iOS 10 data message (sent via FCM)
  [FIRMessaging messaging].remoteMessageDelegate = self;
  #endif
}

[[UIApplication sharedApplication] registerForRemoteNotifications];

Swift

if #available(iOS 10.0, *) {
  // For iOS 10 display notification (sent via APNS)
  UNUserNotificationCenter.current().delegate = self

  let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
  UNUserNotificationCenter.current().requestAuthorization(
    options: authOptions,
    completionHandler: {_, _ in })

  // For iOS 10 data message (sent via FCM)
  FIRMessaging.messaging().remoteMessageDelegate = self

} else {
  let settings: UIUserNotificationSettings =
  UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  application.registerUserNotificationSettings(settings)
}

application.registerForRemoteNotifications()

Subscribe the client app to a topic

Client apps can subscribe to any existing topic, or they can create a new topic. When a client app subscribes to a new topic name (one that does not already exist for your Firebase project), a new topic of that name is created in FCM and any client can subsequently subscribe to it.

The FIRMessaging class handles topic messaging functionality. To subscribe to a topic, call subscribeToTopic:topic from your application's main thread (FCM is not thread-safe):

[[FIRMessaging messaging] subscribeToTopic:@"/topics/news"];
NSLog(@"Subscribed to news topic");

This makes an asynchronous request to the FCM backend and subscribes the client to the given topic. If the subscription request fails initially, FCM retries until it can subscribe to the topic successfully. Each time the app starts, FCM makes sure that all requested topics have been subscribed.

To unsubscribe, call unsubscribeFromTopic:topic, and FCM unsubscribes from the topic in the background.

Receive and handle topic messages

FCM delivers topic messages in the same way as other downstream messages.

Implement AppDelegate application:didReceiveRemoteNotification: to handle notifications received when the client app is in the foreground, and all data messages that are sent to the client. The message is a dictionary of keys and values.

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

  // 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

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

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

  completionHandler(UIBackgroundFetchResultNewData);
}

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

  // 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

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

  // Print full message.
  print(userInfo)

  completionHandler(UIBackgroundFetchResult.newData)
}

Build send requests

From the server side, sending messages to a Firebase Cloud Messaging topic is very similar to sending messages to an individual device or to a user group. The app server sets the to key with a value like /topics/yourTopic. Developers can choose any topic name that matches the regular expression: "/topics/[a-zA-Z0-9-_.~%]+".

To send to combinations of multiple topics, the app server sets the condition key to a boolean condition that specifies the target topics. For example, to send messages to devices that subscribed to TopicA and either TopicB or TopicC:

'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)

FCM first evaluates any conditions in parentheses, and then evaluates the expression from left to right. In the above expression, a user subscribed to any single topic does not receive the message. Likewise, a user who does not subscribe to TopicA does not receive the message. These combinations do receive it:

  • TopicA and TopicB
  • TopicA and TopicC

Conditions for topics support two operators per expression, and parentheses are supported.

For more detail about app server keys, see the reference information for your chosen connection server protocol, HTTP or XMPP. Examples in this page show how to send messages to topics in both HTTP and XMPP.

HTTP POST request

Send to a single topic:

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to" : /topics/foo-bar",
  "priority" : "high",
  "notification" : {
    "body" : "This is a Firebase Cloud Messaging Topic Message!",
    "title" : "FCM Message",
  }
}

Send to devices subscribed to topics "dogs" or "cats":

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "condition": "'dogs' in topics || 'cats' in topics",
  "priority" : "high",
  "notification" : {
    "body" : "This is a Firebase Cloud Messaging Topic Message!",
    "title" : "FCM Message",
  }
}

HTTP response

//Success example:
{
  "message_id": "1023456"
}

//failure example:
{
  "error": "TopicsMessageRateExceeded"
}

XMPP message

Send to a single topic:

<message id="">
  <gcm xmlns="google:mobile:data">

{
  "to" : /topics/foo-bar",
  "priority" : "high",
  "notification" : {
    "body" : "This is a Firebase Cloud Messaging Topic Message!",
    "title" : "FCM Message",
  }
}
  </gcm>
</message>

Send to devices subscribed to topics "dogs" or "cats":

<message id="">
  <gcm xmlns="google:mobile:data">

{
  "condition": "'dogs' in topics || 'cats' in topics",
  "priority" : "high",
  "notification" : {
    "body" : "This is a Firebase Cloud Messaging Topic Message!",
    "title" : "FCM Message",
  }
}

XMPP response

//Success example:
{
  "message_id": "1023456"
}

//failure example:
{
  "error": "TopicsMessageRateExceeded"
}

Expect up to 30 seconds of delay before the FCM Connection Server returns a success or failure response to the topic send requests. Make sure to set the app server's timeout value in the request accordingly.

For the full list of message options, see the reference information for your chosen connection server protocol, HTTP or XMPP.

Next steps

Send feedback about...

Need help? Visit our support page.