How to obtain the notifications' deviceToken in MAUI iOS in C#?

Marc George 171 Reputation points
2023-01-28T18:54:43.4433333+00:00

In executing the following, how do I get the deviceToken?

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

        // Version check
        if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
        {
            // Request notification permissions from the user
            // Request authorization and set handler 
            UNAuthorizationOptions options = 0;
            Action<bool, NSError> completionHandler = CompleteAuthorization;

            UNUserNotificationCenter.Current.RequestAuthorization(options, completionHandler);
        }

        UIApplication.SharedApplication.RegisterForRemoteNotifications();

        // Watch for notifications while the app is active
        UNUserNotificationCenter.Current.Delegate = new UNUserNotificationCenterDelegate();

        return base.FinishedLaunching(application, launchOptions);
    }

Azure Notification Hubs
Azure Notification Hubs
An Azure service that is used to send push notifications to all major platforms from the cloud or on-premises environments.
245 questions
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,608 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Marc George 171 Reputation points
    2023-01-29T16:19:14.8266667+00:00

    Insert the following code into your AppDelegate class. The first method will be called if the registration is completed. Make sure all the certificates, provisioning and entitlement files are present. The second method will be called if the registration fails. The error parameter will give you a clue as to what is wrong with the registration.

    [Foundation.Export("application:didRegisterForRemoteNotificationsWithDeviceToken:")]
        public virtual void RegisteredForRemoteNotifications(UIKit.UIApplication application, NSData deviceToken)
        {
        }
    
    [Export("application:didFailToRegisterForRemoteNotificationsWithError:")]
        public void FailedToRegisterForRemoteNotifications(UIKit.UIApplication application, NSError error)
        {
            int x = 0;
        }
    
    1 person found this answer helpful.
    0 comments No comments