For Apple client apps, you can receive notification and data payloads up to 4096 bytes over the Firebase Cloud Messaging APNs interface.
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 Apple project
If you haven't already, add Firebase to your Apple project.
Upload your APNs authentication key
Upload your APNs authentication key to Firebase. If you don't already have an APNs authentication key, make sure to create one in the Apple Developer Member Center.
-
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 the Apple Developer Member Center) and click Upload.
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
UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { _, _ in } ) application.registerForRemoteNotifications()
Objective-C
[UNUserNotificationCenter currentNotificationCenter].delegate = self; UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge; [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) { // ... }]; [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 Apple platforms typically deliver 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 token(completion:). A non null error is provided if the token retrieval failed in any way.
Swift
Messaging.messaging().token { token, error in if let error = error { print("Error fetching FCM registration token: \(error)") } else if let token = token { print("FCM registration token: \(token)") self.fcmRegTokenMessage.text = "Remote FCM registration token: \(token)" } }
Objective-C
[[FIRMessaging messaging] tokenWithCompletion:^(NSString *token, NSError *error) { if (error != nil) { NSLog(@"Error getting FCM registration token: %@", error); } else { NSLog(@"FCM registration token: %@", token); self.fcmRegTokenMessage.text = token; } }];
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: \(String(describing: 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, or you are building a SwiftUI app, you'll need to
explicitly map your APNs token to the FCM registration token. Implement the
application(_:didRegisterForRemoteNotificationsWithDeviceToken:)
method to
retrieve the APNs token, and then set Messaging
's
apnsToken
property:
Swift
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 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.
Prevent auto initialization
When an FCM registration token is generated, the library uploads the
identifier and configuration data to Firebase. If you want to get an explicit
opt-in from users first, you can prevent token 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 Apple client, you're ready to add message handling and other, more advanced behavior to your app. See these guides for more information: