Send a Notification to a User Segment on iOS

With user segments, you can send notifications to specific groups of users. You can target predefined user segments or custom audiences created in Firebase Analytics.

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.
  • For Cloud Messaging:
    • A physical iOS device.
    • APNs certificate with Push Notifications enabled.
    • In Xcode, enable Push Notifications in App > Capabilities.
  • An Xcode project and its bundle identifier.
  • CocoaPods 1.0.0 or later.

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. If you would like to integrate the Firebase libraries into one of your own projects, you will need to install 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:

    Objective-C

    @import Firebase;
    

    Swift

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

    Objective-C

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

    Swift

    // 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
  UNAuthorizationOptions authOptions =
      UNAuthorizationOptionAlert
      | UNAuthorizationOptionSound
      | UNAuthorizationOptionBadge;
  [[UNUserNotificationCenter currentNotificationCenter]
      requestAuthorizationWithOptions:authOptions
      completionHandler:^(BOOL granted, NSError * _Nullable error) {
      }
   ];

  // For iOS 10 display notification (sent via APNS)
  [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
  // For iOS 10 data message (sent via FCM)
  [[FIRMessaging messaging] setRemoteMessageDelegate:self];
  #endif
}

[[UIApplication sharedApplication] registerForRemoteNotifications];

Swift

if #available(iOS 10.0, *) {
  let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound]
  UNUserNotificationCenter.current().requestAuthorization(
    options: authOptions,
    completionHandler: {_,_ in })

  // For iOS 10 display notification (sent via APNS)
  UNUserNotificationCenter.current().delegate = self
  // 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()

Important: for devices running iOS 10 and above, you must assign your delegate object to the UNUserNotificationCenter object to receive display notifications, and the FIRMessaging object to receive data messages, before your app finishes launching. For example, in an iOS app, you must assign it in the applicationWillFinishLaunching: or applicationDidFinishLaunching: method.

Send a message from the Notifications console

  1. Install and run the app on the target devices.

  2. Open the Notifications tab of the Firebase console and select New Message.

  3. Enter message text.

  4. Select the message target. The dialog displays further options to refine the target based on whether you choose App/App Version, Device Language, or Users in Audience.

After you click Send Message, targeted client devices that have the app in the background receive the notification in the system notifications tray. When a user taps on the notification, the app launcher opens your app.

Console fields and the message payload

When you send a notification message from the Notifications console, Google uses the fields entered in the composer in two ways:

  1. Fields like User segment and Expires determine the message target and delivery options.
  2. Fields like Message text and Custom data are sent to the client in a payload comprised of key/value pairs.

Some of these latter keys are also available through the FCM server API. For example, key/value pairs entered in Custom data are handled as a data payload for the notification. Other fields map directly to keys in the FCM notification payload.

Note that some Notifications console fields are not available through the FCM server API. For example, you can target user segments based on app, app version, or language in ways that are not available using the to field in the server API.

The keys that the Notifications console sends to clients are:

Key Console field label Description
notification.title Message title Indicates notification title.
notification.body Message text Indicates notification body text.
data Custom data Key/value pairs that you define. These are delivered as a data payload for the app to handle.

Keys that determine message delivery include:

Key Console field label Description
priority Priority

Sets the priority of the message.

For more information, see Setting the priority of a message.

sound Sound

Indicates a sound to play when the device receives a notification.

time_to_live Expires

This parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline. For more information, see Setting the lifespan of a message.

Receive and handle notifications

If you want to receive notifications when your app is in the foreground, you need to add some message handling logic.

For devices running iOS 9 and below, 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

// To receive notifications for iOS 9 and below.
- (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.
  NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]);

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

Swift

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.
  print("Message ID: \(userInfo["gcm.message_id"]!)")

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

For devices running iOS 10 and above, implement UNUserNotificationCenterDelegate userNotificationCenter:willPresentNotification:withCompletionHandler: to handle notifications received when the client app is in the foreground. The message is a UNNotification object. Implement FIRMessagingDelegate applicationReceivedRemoteMessage: to handle all data messages that are sent to the client. The message is a FIRMessagingRemoteMessage object.

Objective-C

// Receive displayed notifications for iOS 10 devices.
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  // Print message ID.
  NSDictionary *userInfo = notification.request.content.userInfo;
  NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]);

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

// Receive data message on iOS 10 devices.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  // Print full message
  NSLog(@"%@", [remoteMessage appData]);
}
#endif

Swift

@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
    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

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

extension AppDelegate : FIRMessagingDelegate {
  // Receive data message on iOS 10 devices.
  func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print("%@", remoteMessage.appData)
  }
}

Send feedback about...

Need help? Visit our support page.