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 Apple client app
for FCM.
Add Firebase to your Apple 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
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 Apple app, you need to create a Firebase
project to connect to your app. Visit
Understand Firebase Projects
to learn more about
Firebase projects.
Create a Firebase project
-
In the
Firebase console
, click
Add project
.
-
To add Firebase resources to an
existing
Google Cloud project, enter its
project name or select it from the dropdown menu.
-
To create a new project, enter the desired project name. You can also optionally
edit the project ID displayed below the project name.
-
If prompted, review and accept the
Firebase terms
.
-
Click
Continue
.
-
(Optional)
Set up Google Analytics for your project, which enables you
to have an optimal experience using any of the following Firebase products:
Either select an existing
Google Analytics account
or to create a new account.
If you create a new account, select your
Analytics reporting location
, then accept
the data sharing settings and Google Analytics terms for your project.
-
Click
Create project
(or
Add Firebase
, if you're using an
existing Google Cloud project).
Firebase automatically provisions resources for your Firebase project. When
the process completes, you'll be taken to the overview page for your Firebase
project in the Firebase console.
Register your app with Firebase
To use Firebase in your Apple app, you need to register your app with your
Firebase project. Registering your app is often called "adding" your app to your
project.
Go to the
Firebase console
.
In the center of the 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
bundle ID
field.
What's a bundle ID, and where do you find it?
A
bundle ID
uniquely identifies an application in Apple's ecosystem.
Find your bundle ID: open your project 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 bundle ID
(for example,
com.yourcompany.yourproject
).
Be aware that the bundle ID value is case-sensitive, and it cannot be
changed for this Firebase app after it's registered with your
Firebase project.
(Optional)
Enter other app information:
App nickname
and
App Store ID
.
How are the
App nickname
and the
App Store ID
used within Firebase?
Click
Register app
.
Add a Firebase configuration file
Click
Download GoogleService-Info.plist
to obtain your Firebase Apple
platforms config file (
GoogleService-Info.plist
).
What do you need to know about this config file?
The Firebase config file contains unique, but non-secret identifiers for
your project. To learn more about this config file, visit
Understand Firebase
Projects
.
You can download your
Firebase config
file
again at any time.
Make sure the config file name 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
Use Swift Package Manager to install and manage Firebase dependencies.
- In Xcode, with your app project open, navigate to
File > Add Packages
.
- When prompted, add the Firebase Apple platforms SDK repository:
https://github.com/firebase/firebase-ios-sdk.git
- Choose the Firebase Cloud Messaging library.
- Add the
-ObjC
flag to the
Other Linker Flags
section of your target's build settings.
-
For an optimal experience with Firebase Cloud Messaging, we recommend
enabling Google Analytics
in your Firebase project and adding the Firebase SDK for Google Analytics to your app. You can
select either the library without IDFA collection or with IDFA collection.
-
When finished, Xcode will automatically begin resolving and downloading your
dependencies in the background.
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
.
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
FirebaseCore
module in your
UIApplicationDelegate
, as well as any other
Firebase modules
your app delegate uses.
For example, to use Cloud Firestore and Authentication:
SwiftUI
import SwiftUI
import FirebaseCore
import FirebaseFirestore
import FirebaseAuth
// ...
Swift
import FirebaseCore
import FirebaseFirestore
import FirebaseAuth
// ...
Objective-C
@import FirebaseCore;
@import FirebaseFirestore;
@import FirebaseAuth;
// ...
- Configure a
FirebaseApp
shared instance in your app delegate's
application(_:didFinishLaunchingWithOptions:)
method:
SwiftUI
// Use Firebase library to configure APIs
FirebaseApp.configure()
Swift
// Use Firebase library to configure APIs
FirebaseApp.configure()
Objective-C
// Use Firebase library to configure APIs
[FIRApp configure];
- If you're using SwiftUI, you must create an application delegate and attach it
to your
App
struct via
UIApplicationDelegateAdaptor
or
NSApplicationDelegateAdaptor
. You must also disable app delegate swizzling. For
more information, see the
SwiftUI instructions
.
SwiftUI
@main
struct YourApp: App {
// register app delegate for Firebase setup
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
NavigationView {
ContentView()
}
}
}
}
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
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
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 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.
Send a notification message
Install and run the app on the target device. On Apple devices, you'll need
to accept the request for permission to receive remote notifications.
Make sure the app is in the background on the device.
In the Firebase console, open the
Messaging page
.
If this is your first message, select
Create your first
campaign
.
- Select
Firebase Notification messages
and select
Create
.
Otherwise, on the
Campaigns
tab, select
New campaign
and then
Notifications
.
Enter the message text. All other fields are optional.
Select
Send test message
from the right pane.
In the field labeled
Add an FCM registration token
, enter the registration
token you obtained in a previous section of this guide.
Select
Test
.
After you select
Test
, the targeted client device (with the app in
the background) should receive the notification.
For insight into message delivery to your app, see
the
FCM reporting dashboard
, which records the
number of messages sent and opened on Apple 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: