Firebase Cloud Messaging
Prerequisites
- iOS 8+
- APNs provisioned and uploaded to Firebase
- Push Notifications entitlement enabled for the project
Configure Cloud Messaging
Add the following line of code somewhere in your app. This will typically reside in your AppDelegate's FinishedLaunching
method (don't forget to import Firebase.Core
namespace):
Firebase.Core.App.Configure();
Register for remote notifications
At startup or at desired point in your application flow, register your application for remote notifications. Call the RegisterForRemoteNotifications
method:
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) {
// For iOS 10 display notification sent via APNs
UNUserNotificationCenter.Current.Delegate = this;
var authOptions = UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound;
UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) => {
// do something
});
} else {
// iOS 9 or before
var allNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound;
var settings = UIUserNotificationSettings.GetSettingsForTypes (allNotificationTypes, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings (settings);
}
UIApplication.SharedApplication.RegisterForRemoteNotifications();
::: info Note
For devices running iOS 10 and above, you must assign your delegate object to the UNUserNotificationCenter
object to receive display notifications, and the Messaging
object to receive data messages before your app finishes launching. It must be assigned in the WillFinishLaunching
or FinishedLaunching
method.
:::
Access the registration token
By default, the FCM SDK will generate a registration token for the app instance on initial startup. This token allows you to target notification messages to this particular instance of the app.
FCM provides a registration token via the DidReceiveRegistrationToken
method of the Messaging
delegate on each app startup. During the first app start, and in all situations where the token is changed, the FCM SDK will retrieve a new token. In both cases, the FCM SDK will call DidReceiveRegistrationtoken
found in the IMessagingDelegate
interface.
The registration token may change when:
- The app is restorted on a new device
- The user uninstalls or reinstalls the app
- The user clears app data
Set the Messaging Delegate
To receive registration tokens on app start, implement the IMessagingDelegate
interface in a class and provide it to Messaging
's Delegate
property after calling App.Configure()
. If your application delegate conforms to the ImessagingDelegate
interface, you can set the delegate on FinishedLaunching
to itself:
Messaging.SharedInstance.Delegate = this;
Receive the current registration token
Registration tokens are delivered via the IMessagingDelegate
method DidReceiveRegistrationToken
. This method is called once per app start with an FCM token. When this method is called, it is the ideal to:
- If the token is new, send it to your application server or Kettle via
Kettle.Shared.PushToken =
. It is recommended to implement server logic to determine whether the token is new if you're handling this token yourself. - Subscribe the registration token to topics. This is required for new subscriptions or for situations where the user has re-installed the app. You should register the token to a topic called
kettle
to allow batched push notifications.
After this delegate method is called, the token is available via the FcmToken
property of the Messaging
class. Prior to this delegate method call, the property may be null
.
var token = Messaging.SharedInstance.FcmToken ?? "";
Console.WriteLine($"FCM token: {token}");
Monitor token generation & subscribe to topic
To be notified whenever the token is updated, supply a class conforming to the IMessagingDelegate
interface and set it to Messaging Delegate
property. The following example registers the delegate and adds the proper interface method:
[Export ("messaging:didReceiveRegistrationToken:")]
public void DidReceiveRegistrationToken (Messaging messaging, string fcmToken)
{
Console.WriteLine ($"Firebase registration token: {fcmToken}");
// Apply the token to a subscription group for Kettle.
// Send the token to your application server if necessary.
// Note: This callback is fired at each app startup and whenever a new token is generated.
// Please note that this can be done somewhere else in the application flow.
// Make sure the token has been received via this method before subscribing.
// The subscribe method must be called from your application's main thread, since FCM is not thread-safe.
// Non-async version
Messaging.SharedInstance.Subscribe("kettle", (error) => {
// Do something on error.
});
Console.WriteLine("Subscribed to topic Kettle");
// async/away version
try {
await Messaging.SharedInstance.SubscribeAsync("kettle");
Console.WriteLine("Subscribed to topic Kettle");
} catch (NSErrorException ex) {
// Do something on error.
}
}
Receive Messages
Once your app is installed on a device, it can receive messaged through the FCM APNs interface. You can immediately start sending notifications to user segments with the Notifications composer or your application server can send messaged with a notification payload through the APNs interface.
Handling messages received through the FCM APNs interface is likely to cover most typical user cases.
Handle messages received through the FCM APNs interface
When your app is in the background, iOS directs messages with the notification
key to the system tray. Tapping on this notifications opens the app and the content of the notification is passed to the DidReceiveRemoteNotification
method in the AppDelegate
.
Implement AppDelegate DidReceiveRemoteNotification
:
public override void ReceivedRemoteNotification (UIApplication application, NSDictionary userInfo)
{
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
//Messaging.SharedInstance.AppDidReceiveMessage (userInfo);
// Print full message.
Console.WriteLine (userInfo);
}
public override void DidReceiveRemoteNotification (UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
//Messaging.SharedInstance.AppDidReceiveMessage (userInfo);
// Print full message.
Console.WriteLine (userInfo);
completionHandler (UIBackgroundFetchResult.NewData);
}
Send Messages
Silent Push Payload
{
"to": "/topics/kettle",
"priority": "high",
"content_available": true,
"data": {
"kettle": true,
},
}