For iOS client apps, you can implement Firebase Cloud Messaging in two complementary ways:
Receive basic push messages up to 4KB over the Firebase Cloud Messaging APNs interface.
Send messages upstream and/or receive downstream data payloads up to 4KB in foregrounded apps.
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 SDK 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 FCM specifically, you'll need to upload your APNs authentication key and register for remote notifications.
Prerequisites
Install the following:
- Xcode 10.1 or later
- CocoaPods 1.4.0 or later
Make sure that your project meets the following requirements:
- Your project must target iOS 8 or later.
- Swift projects must use Swift 3.0 or later.
Set up a physical iOS device or the iOS simulator for running your app.
For Cloud Messaging, complete the following tasks:
- Set up a physical iOS device.
- Obtain an Apple Push Notification Authentication Key for your Apple Developer account.
- Enable Push Notifications in XCode under App > Capabilities.
For all other Firebase products, you can use either a physical iOS device or the iOS simulator.
Sign into Firebase using your Google account.
If you don't already have an Xcode project and just want to try out a Firebase product, you can download one of our quickstart samples.
Create a Firebase project
Before you can add Firebase to your iOS app, you need to create a Firebase project to connect to your iOS app. Visit Understand Firebase Projects to learn more about Firebase projects.
Register your app with Firebase
After you have a Firebase project, you can add your iOS app to it.
Visit Understand Firebase Projects to learn more about best practices and considerations for adding apps to a Firebase project, including how to handle multiple build variants.
In center of the Firebase console's project overview page, click the iOS icon ( ) to launch the setup workflow.
If you've already added an app to your Firebase project, click Add app to display the platform options.
Enter your app's bundle ID in the iOS bundle ID field. Find your bundle ID, as follows:
Open your app in XCode.
Select the top-level app in the project navigator, then select the General tab.
The value of the Bundle Identifier field is the iOS bundle ID (for example,
com.yourcompany.yourproject
).
(Optional) Enter other app information as prompted by the setup workflow.
App nickname: An internal, convenience identifier that is only visible to you in the Firebase console
App Store ID: Used by Firebase Dynamic Links to redirect users to your App Store page and by Google Analytics to import conversion events into Google Ads. If your app doesn't yet have an App Store ID, you can add the ID later in your Project Settings.
Click Register app.
Add a Firebase configuration file
Click Download GoogleService-Info.plist to obtain your Firebase iOS config file (
GoogleService-Info.plist
).You can download your Firebase iOS config file again at any time.
Make sure the config file is not appended with additional characters, like
(2)
.
Move your config file into the root of your Xcode project. If prompted, select to add the config file to all targets.
If you have multiple bundle IDs in your project, you must associate each bundle
ID with a registered app in the Firebase console so that each app can have
its own GoogleService-Info.plist
file.
Add Firebase SDKs to your app
We recommend using CocoaPods to install the Firebase libraries. However, if you'd rather not use CocoaPods, you can integrate the SDK frameworks directly.
Note that if you're using one of the quickstart samples, the Xcode project and Podfile (with pods) are already present, but you'll still need to add your Firebase configuration file and install the pods.
You can add any of the supported Firebase products to your iOS app.
Create a Podfile if you don't already have one:
cd your-project-directory
pod init
To your Podfile, add the Firebase pods that you want to use in your app.
For an optimal experience with Firebase Cloud Messaging, we recommend enabling Google Analytics in your project. As part of setting up Google Analytics, you need to add the Firebase SDK for Google Analytics to your app.
Analytics enabled
# Add the Firebase pod for Google Analytics pod 'Firebase/Analytics'
# Add the pod for Firebase Cloud Messaging pod 'Firebase/Messaging'Analytics not enabled
# Add the pod for Firebase Cloud Messaging pod 'Firebase/Messaging'
Install the pods, then open your
.xcworkspace
file to see the project in Xcode:pod install
open your-project.xcworkspace
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.
-
Inside your project in the Firebase console, select the gear icon, select Project Settings, and then select the Cloud Messaging tab.
-
In APNs authentication key under iOS app configuration, click the Upload button.
-
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:
- Import the Firebase module in your
UIApplicationDelegate
:Swift
import Firebase
Objective-C
@import Firebase;
- Configure a
FirebaseApp
shared instance, typically in your app'sapplication: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. CallregisterForRemoteNotifications
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
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 instance 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.
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 set FIRMessaging
's APNSToken
property:
Swift
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { Messaging.messaging().apnsToken = deviceToken }
Objective-C
// With "FirebaseAppDelegateProxyEnabled": NO - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [FIRMessaging messaging].APNSToken = deviceToken; }
After the FCM registration token is generated, you can access it 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.
Prevent auto initialization
FCM generates an Instance ID, which is used as a registration
token within FCM. When an Instance ID is generated the library will upload the
identifier and configuration data to Firebase.If you want to get an explicit
opt-in before using Instance ID, you can prevent generation at configure time by
disabling FCM. To do this, add a metadata value to your Info.plist
(not your
GoogleService-Info.plist
):
FirebaseMessagingAutoInitEnabled = NO
To re-enable FCM, you can make a runtime call:
Swift
Messaging.messaging().autoInitEnabled = true
Objective-C
[FIRMessaging messaging].autoInitEnabled = YES;
This value persists across app restarts once set.
Next steps
After you have set up your iOS client, you're ready to add message handling and other, more advanced behavior to your app. See these guides for more information: