Skip to content

[iOS] Working with push notifications

Elvin (Tharindu) Thudugala edited this page Jul 14, 2024 · 3 revisions

When using push notifications and wanting to support different actions in the app when the user taps various push notifications.

You need to inherit and create a class from Plugin.LocalNotification.Platforms.UserNotificationCenterDelegate under iOS platform folder or project

public class CustomUserNotificationCenterDelegate : UserNotificationCenterDelegate
{
    public override void DidReceiveNotificationResponse(UNUserNotificationCenter center,
        UNNotificationResponse response,
        Action completionHandler)
    {
        // If the notification is typed Plugin.LocalNotification.NotificationRequest
        // Call the base method else handle it by yourself.

        var notificationRequest = LocalNotificationCenter.GetRequest(response.Notification.Request.Content);
        if (notificationRequest is not null)
        {
            base.DidReceiveNotificationResponse(center, response, completionHandler);
        }
        else
        {
            // Write your code here
        }
    }

    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification,
        Action<UNNotificationPresentationOptions> completionHandler)
    {
        // If the notification is typed Plugin.LocalNotification.NotificationRequest
        // Call the base method else handle it by yourself.

        if(notification is null)
        {
            return;
        }

        var notificationRequest = LocalNotificationCenter.GetRequest(notification.Request.Content);

        if (notificationRequest is not null)
        {
            base.WillPresentNotification(center, notification, completionHandler);
        }
        else
        {
            // Write your code here
        }
    }
}

Then pass this to the plugin when you call SetCustomUserNotificationCenterDelegate method

.Net Maui

public static MauiApp CreateMauiApp()
{
	var builder = MauiApp.CreateBuilder();
	builder
		.UseMauiApp<App>()
		.........
		.UseLocalNotification(config =>
                {
                   config.AddiOS(iOS =>
                   {
#if IOS
                       // If you want to handle push notifications
                       iOS.SetCustomUserNotificationCenterDelegate(new CustomUserNotificationCenterDelegate());
#endif
                   });
                });
			
	return builder.Build();
}

Xamarin

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init();

    // If you want to handle push notifications
    LocalNotificationCenter.SetCustomUserNotificationCenterDelegate(new CustomUserNotificationCenterDelegate());

    LoadApplication(new App());

    return base.FinishedLaunching(app, options);
}