Request Notifications Permission in a .Net MAUI App for IOS

439 Views Asked by At

I have the code in hand from other sources to send a local notification using Plugin.LocalNotification. Good stuff. The code works on Windows. It does not appear to work on IOS (using Hot Restart).

I came across other sources that suggest it is necessary to request the notification permission. OK

var notificationsEnabled = await LocalNotificationCenter.Current.AreNotificationsEnabled();

This indicates that notifications are not enabled in my app.

How then to request the Notification permission?

1

There are 1 best solutions below

0
Bill Needels On

This worked on my Hot Restart-deployed IOS app: in Platforms/iOS/AppDelegate.cs, use the following code derived from Dima Ordenov's MauiSamples

using UIKit;
using UserNotifications;

...

public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
    RegisterForRemoteNotifications(application);

    return base.FinishedLaunching(application, launchOptions);
}

/// <summary>
/// Reqeust permission for notifications
/// </summary>
/// <param name="application"></param>
/// <remarks>from https://github.com/DimaOrdenov/MauiSamples/blob/main/MauiPushNotifications/Platforms/iOS/AppDelegate.cs</remarks>
private void RegisterForRemoteNotifications(UIApplication application)
{
    UNUserNotificationCenter.Current.RequestAuthorization(
        UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound,
        (isSuccess, error) =>
        {
            if (error != null)
            {
                // no op, not going to do anything about this for now
            }
        });

    application.RegisterForRemoteNotifications();
}