Handle Firebase Push Notifications Tap in .NET MAUI
When you start an app from a notification, you must preserve the user’s expected navigation experience. Tapping Back should take the user back through the app’s Home screen.
The basic approach is to set the tap behavior for your notification.
Setup
In my previous posts, I demonstrated how to setup your .NET MAUI project to enable receiving push notifications with Firebase Cloud Messaging. If you haven’t seen it yet, please check it out here.
Notification Tapped Event
In your MauiProgram.cs
, register NotificationTapped
event:
CrossFirebaseCloudMessaging.Current.NotificationTapped += (sender, e) =>
{
System.Diagnostics.Debug.WriteLine("Tapped");
};
Navigation
To navigate into a specific page, you can use Shell.GoToAsync
method:
CrossFirebaseCloudMessaging.Current.NotificationTapped += (sender, e) =>
{
System.Diagnostics.Debug.WriteLine("Tapped");
Shell.Current.GoToAsync(nameof(DetailsPage));
};
Passing the notification
You may want to pass some data and show the details about the notification when the page opens via push notification.
Notification data can be passed with a GoToAsync
overload that specifies an IDictionary<string, object>
argument:
CrossFirebaseCloudMessaging.Current.NotificationTapped += (sender, e) =>
{
System.Diagnostics.Debug.WriteLine("Tapped");
var navigationParameter = new Dictionary<string, object>
{
{ "Notification", e.Notification}
};
Shell.Current.GoToAsync(nameof(DetailsPage), navigationParameter);
};
Process notification
In this example, passed data can be received by implementing the IQueryAttributable
interface on the receiving class:
public partial class DetailsPage : ContentPage, IQueryAttributable
{
public void ApplyQueryAttributes(IDictionary<string, object> query)
{
var notification = query["Notification"] as FCMNotification;
var title = notification.Data["Title"];
var body = notification.Data["Body"];
Shell.Current.DisplayAlert(title, body, "OK");
}
}
Here’s a quick demo of how it works:
Custom data
Custom data, also known as custom key-value pairs or payload data, refers to the data that you can send along with your FCM messages. You can also include custom data as a JSON object.
You could include custom data such as the ID of the notification, the message to display, or any other relevant information. When the user receives the notification and taps on it, your app can retrieve this custom data and use it to perform the intended action.
Closing thoughts
Push notifications are effective way for mobile apps to engage with their users and keep them up-to-date with the latest information. When a user taps on a push notification, the app should be able to handle this event appropriately.
Well, that’s it on how to handle Firebase Push Notifications tap in .NET MAUI! You can check out the source code example on my GitHub.
If you find this useful, make sure to follow for more content like this!