Send a test message to a backgrounded iOS app

To get started with FCM, build out the simplest use case: sending a test notification message from the Notifications composer to a development device when the app is in the background on the device. This page lists all the steps to achieve this, from setup to verification — it may cover steps you already completed if you have set up an iOS client app for FCM.

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 FCM specifically, you'll need to upload your APNs authentication key and register for remote notifications.

Prerequisites

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

  • Xcode 9.2 or later
  • An Xcode project targeting iOS 8 or above
  • Swift projects must use Swift 3.0 or later
  • The bundle identifier of your app
  • CocoaPods 1.4.0 or later
  • For Cloud Messaging:
    • A physical iOS device
    • An Apple Push Notification Authentication Key for your Apple Developer account
    • 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.

To create a Firebase project:

  1. Go to the Firebase console.

  2. Click Add project, then select or enter a Project name.

    • If you have an existing Google project associated with your app, select the project from the Project name dropdown menu.
    • If you don't have an existing Google project, enter a new Project name.
  3. (Optional) Edit the Project ID.

    Firebase automatically assigns a unique ID to your Firebase project. This identifier displays in publicly visible Firebase services, for example:

    • Default database URL — your-project-id.firebaseio.com
    • Default hosting subdomain — your-project-id.firebaseapp.com
  4. Follow the remaining setup steps, then click Create project (or Add Firebase, if you're using an existing Google project).

Firebase automatically provisions resources for your Firebase project. The process typically takes a few minutes. When the process completes, you'll be taken to the overview page for your Firebase project in the Firebase console.

Now that you have a project, you can add your iOS app to it:

  1. 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.
  2. 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.
  3. During the process, you'll download a GoogleService-Info.plist file. You can download this file again at any time.
  4. After you add the initialization code, run your app to send verification to the Firebase console that you've successfully installed Firebase.

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 without using CocoaPods.

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 Google Analytics for Firebase. 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 authentication key

Upload your APNs authentication key to Firebase. If you don't already have an APNs authentication key, see Configuring APNs with FCM.

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

  2. In APNs authentication key under iOS app configuration, click the Upload button.

  3. Browse to the location where you saved your key, select it, and click Open. Add the key ID for the key (available in Certificates, Identifiers & Profiles in the Apple Developer Member Center) and click Upload.

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:

    Swift

    import Firebase
    

    Objective-C

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

    Swift

    // Use Firebase library to configure APIs
    FirebaseApp.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:

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 })
} else {
  let settings: UIUserNotificationSettings =
  UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
  application.registerUserNotificationSettings(settings)
}

application.registerForRemoteNotifications()

Objective-C

if ([UNUserNotificationCenter class] != nil) {
  // iOS 10 or later
  // 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) {
        // ...
      }];
} else {
  // iOS 10 notifications aren't available; fall back to iOS 8-9 notifications.
  UIUserNotificationType allNotificationTypes =
  (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
  UIUserNotificationSettings *settings =
  [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
  [application registerUserNotificationSettings:settings];
}

[application registerForRemoteNotifications];

Access the registration token

To send a message to a specific device, you need to know that device's registration token. Because you'll need to enter the token in a field in the Notifications composer to complete this tutorial, make sure to copy the token or securely store it after you retrieve it.

By default, the FCM SDK generates a registration token for the client app instance on app launch. Similar to the APNs device token, this token allows you to send targeted notifications to any particular instance of your app.

In the same way that iOS typically delivers an APNs device token on app start, FCM provides a registration token via FIRMessagingDelegate's messaging:didReceiveRegistrationToken: method. The FCM SDK retrieves a new or existing token during initial app launch and whenever the token is updated or invalidated. In all cases, the FCM SDK calls messaging:didReceiveRegistrationToken: with a valid token.

The registration token may change when:

  • The app is restored on a new device
  • The user uninstalls/reinstall the app
  • The user clears app data.

Set the messaging delegate

To receive registration tokens, implement the messaging delegate protocol and set FIRMessaging's delegate property after calling [FIRApp configure]. For example, if your application delegate conforms to the messaging delegate protocol, you can set the delegate on application:didFinishLaunchingWithOptions: to itself.

Swift

Messaging.messaging().delegate = self

Objective-C

[FIRMessaging messaging].delegate = self;

Fetching the current registration token

Registration tokens are delivered via the method messaging:didReceiveRegistrationToken:. This method is called generally once per app start with registration token. When this method is called, it is the ideal time to:

  • If the registration token is new, send it to your application server.
  • Subscribe the registration token to topics. This is required only for new subscriptions or for situations where the user has re-installed the app.

You can retrieve the token directly using instanceIDWithHandler:. This callback provides an InstanceIDResult, which contains the token. A non null error is provided if the InstanceID retrieval failed in any way.

Swift

InstanceID.instanceID().instanceID { (result, error) in
  if let error = error {
    print("Error fetching remote instange ID: \(error)")
  } else if let result = result {
    print("Remote instance ID token: \(result.token)")
    self.instanceIDTokenMessage.text  = "Remote InstanceID token: \(result.token)"
  }
}

Objective-C

[[FIRInstanceID instanceID] instanceIDWithHandler:^(FIRInstanceIDResult * _Nullable result,
                                                    NSError * _Nullable error) {
  if (error != nil) {
    NSLog(@"Error fetching remote instance ID: %@", error);
  } else {
    NSLog(@"Remote instance ID token: %@", result.token);
    NSString* message =
      [NSString stringWithFormat:@"Remote InstanceID token: %@", result.token];
    self.instanceIDTokenMessage.text = message;
  }
}];

Generally, the token is available locally, so this method does not open a network connection. You can use this method at any time to access the token instead of storing it.

Monitor token refresh

To be notified whenever the token is updated, supply a delegate conforming to the messaging delegate protocol. The following example registers the delegate and adds the proper delegate method:

Swift

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
  print("Firebase registration token: \(fcmToken)")

  let dataDict:[String: String] = ["token": fcmToken]
  NotificationCenter.default.post(name: Notification.Name("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.
}

Objective-C

- (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.
}

Alternatively, you can listen for an NSNotification named kFIRMessagingRegistrationTokenRefreshNotification rather than supplying a delegate method. The token property always has the current token value.

Send a notification message

  1. Install and run the app on the target device. You'll need to accept the request for permission to receive remote notifications.

  2. Make sure the app is in the background on the device.

  3. Open the Notifications composer and select New Message.

  4. Enter the message text.

  5. Select Test on Device.

  6. In the field labeled Add an instance ID token, enter the registration token you obtained in a previous section of this guide.

  7. Click Test

After you click Test, the targeted client device (with the app in the background) should receive the notification in the notification center.

For insight into message delivery to your app, see the FCM reporting dashboard, which records the number of messages sent and opened on iOS and Android devices, along with data for "impressions" (notifications seen by users) for Android apps.

Next steps

To go beyond notification messages and add other, more advanced behavior to your app, see:

Send feedback about...

Need help? Visit our support page.