Setting Up a Firebase Cloud Messaging Client App on iOS

For iOS client apps, you can implement Firebase Cloud Messaging in two complementary ways:

  • Receive basic push messages up to 2KB over the Firebase Cloud Messaging APNs interface.

  • Send messages upstream and/or receive downstream payloads up to 4KB.

To write your client code in Objective-C or Swift, we recommend that you use the FIRMessaging API. The quickstart example provides sample code for both languages.

Method swizzling in Firebase Cloud Messaging

The FCM API performs method swizzling in two key areas: mapping your APNs token to the FCM registration token and capturing analytics data during downstream message callback handling. Developers who prefer not to use swizzling can disable it by adding the flag FirebaseAppDelegateProxyEnabled in the app’s Info.plist file and setting it to NO (boolean value). Relevant areas of the guides provide code examples, both with and without method swizzling enabled.

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.

Receive messages through the FCM APNs interface

Once your client app is installed on a device, it can receive messages through the FCM APNs interface. You can immediately start sending notifications to user segments with the Notifications console, or your application server can send messages with a notification payload through the APNs interface.

Access the registration token

By default, the FCM SDK generates a registration token for the client app instance on initial startup of your app. If you want to target single devices, or create device groups for FCM, you'll need to access this token.

This section describes how to retrieve the token and how to monitor changes to the token. Because the token could be rotated after initial startup, you are strongly recommended to retrieve the latest updated registration token unless you have a specific need to directly retrieve the current token.

The registration token may change when:

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

Retrieve the current registration token

When you need to retrieve the current token, call [[FIRInstanceID instanceID] token]. This method returns null if the token has not yet been generated.

Objective-C

NSString *refreshedToken = [[FIRInstanceID instanceID] token];

Swift

let token = FIRInstanceID.instanceID().token()!

Monitor token generation

You can access the token's updated value by adding an observer that listens to kFIRInstanceIDTokenRefreshNotification then retrieve the token from the observer's selector. In this example, tokenRefreshNotification is the selector used to handle the callback:

Objective-C

- (void)tokenRefreshNotification:(NSNotification *)notification {
  // Note that this callback will be fired everytime a new token is generated, including the first
  // time. So if you need to retrieve the token as soon as it is available this is where that
  // should be done.
  NSString *refreshedToken = [[FIRInstanceID instanceID] token];
  NSLog(@"InstanceID token: %@", refreshedToken);

  // Connect to FCM since connection may have failed when attempted before having a token.
  [self connectToFcm];

  // TODO: If necessary send token to application server.
}

Swift

func tokenRefreshNotification(_ notification: Notification) {
  if let refreshedToken = FIRInstanceID.instanceID().token() {
    print("InstanceID token: \(refreshedToken)")
  }

  // Connect to FCM since connection may have failed when attempted before having a token.
  connectToFcm()
}

kFIRInstanceIDTokenRefreshNotification fires when tokens are generated, so calling [[FIRInstanceID instanceID] token]in its context ensures that you are accessing a current, available registration token.

See the Instance ID API reference for full detail on the API.

Swizzling disabled: mapping your APNs token and registration token

If you have disabled method swizzling, you'll need to explicitly map your APNs token to the FCM registration token. Override the methods didRegisterForRemoteNotificationsWithDeviceToken to retrieve the APNs token, and then call setAPNSToken.

Provide your APNs token and the token type in setAPNSToken:type:. Make sure that the value of type is correctly set: FIRInstanceIDAPNSTokenTypeSandbox for the sandbox environment, or FIRInstanceIDAPNSTokenTypeProd for the production environment. If you don't set the correct type, messages are not delivered to your app.

Objective-C

// With "FirebaseAppDelegateProxyEnabled": NO
- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
             [FIRInstanceID instanceID] setAPNSToken:deviceToken
                                                type:FIRInstanceIDAPNSTokenTypeSandbox];
}

Swift

func application(application: UIApplication,
                   didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
  FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenTypeSandbox)
}

After the Instance ID token is generated, you can access the token and listen for refresh events using the same methods as with swizzling enabled.

Import existing user APNs tokens

If you have an existing user base that you want to onboard to an FCM client app, use the batchImport API provided by Instance ID. With this API, you can bulk import existing iOS APNs tokens into FCM, mapping them to new, valid registration tokens.

Receive messages through FCM

To receive or send messages through FCM (not just the APNs interface), you'll need to connect to the FCM service. Connect when your application becomes active and whenever a new registration token is available. Once your app is connected, FCM ignores subsequent attempts to connect.

Objective-C

- (void)connectToFcm {
  [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
    if (error != nil) {
      NSLog(@"Unable to connect to FCM. %@", error);
    } else {
      NSLog(@"Connected to FCM.");
    }
  }];
}

Swift

func connectToFcm() {
  FIRMessaging.messaging().connect { (error) in
    if (error != nil) {
      print("Unable to connect with FCM. \(error)")
    } else {
      print("Connected to FCM.")
    }
  }
}

After your app is connected, you can send downstream and upstream messages and use topic messaging and device group messaging. When your app goes into the background, disconnect from FCM:

Objective-C

- (void)applicationDidEnterBackground:(UIApplication *)application {
  [[FIRMessaging messaging] disconnect];
  NSLog(@"Disconnected from FCM");
}

Swift

func applicationDidEnterBackground(_ application: UIApplication) {
  FIRMessaging.messaging().disconnect()
  print("Disconnected from FCM.")
}

Next steps

To go beyond simple notifications and add other, more advanced behavior to your app, see the guides for sending messages from an app server:

Keep in mind that you'll need a server implementation to take advantage of these features.

Send feedback about...

Need help? Visit our support page.