'UILocalNotification' is obsoleted on: 'ios' 10.0 and later (Use 'UserNotifications.UNNotificationRequest' instead.)

Kim Strasser 661 Reputation points
2023-01-30T12:24:14.4933333+00:00

I want to receive and display push notifications on my iPhone/iPad but I get the following message in Visual Studio for Mac:

'UILocalNotification' is obsoleted on: 'ios' 10.0 and later (Use 'UserNotifications.UNNotificationRequest' instead.)

I use .NET 7.0, Target iOS version 16.1 and Minimum iOS version 15.0 in my iOS project.

Program.cs:

public override void FinishedLaunching(UIApplication app)
{
    var authOptions = UserNotifications.UNAuthorizationOptions.Alert | UserNotifications.UNAuthorizationOptions.Badge | UserNotifications.UNAuthorizationOptions.Sound;
                    UserNotifications.UNUserNotificationCenter.Current.RequestAuthorization(authOptions, (granted, error) =>
{
    Console.WriteLine(granted);
});
}

public override void ReceivedRemoteNotification(UIApplication application, NSDictionary userInfo)
{
    ProcessNotification(userInfo, false);
}

void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
{
            // Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
            if (null != options && options.ContainsKey(new NSString("aps")))
            {
                //Get the aps dictionary
                NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;
                string alert = string.Empty;
                string MessageTitle = "";
                string MessageBody = "";

                if (aps.ContainsKey(new NSString("alert")))
                {
                    MessageTitle = ((options["aps"] as NSDictionary)["alert"] as NSDictionary)["title"] as NSString;
                    MessageBody = ((options["aps"] as NSDictionary)["alert"] as NSDictionary)["body"] as NSString;
                }

                if (!fromFinishedLaunching)
                {
                    //Manually show an alert
                    if (!string.IsNullOrEmpty(MessageTitle) || !string.IsNullOrEmpty(MessageBody))
                    {           
                        UILocalNotification notification = new UILocalNotification();
                        notification.FireDate = NSDate.Now;
                        notification.AlertTitle = MessageTitle;
                        notification.AlertBody = MessageBody;
                        notification.TimeZone = NSTimeZone.DefaultTimeZone;
                        notification.SoundName = UILocalNotification.DefaultSoundName;
                        UIApplication.SharedApplication.ScheduleLocalNotification(notification);
                    }
                }
            }
}

How can I use UserNotifications instead UILocalNotification to display the received push notification?

I have already tried it with UserNotifications.UNNotificationRequest notification = new UserNotifications.UNNotificationRequest(); but it's not working.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,860 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
0 comments No comments
{count} votes

Accepted answer
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 26,221 Reputation points Microsoft Vendor
    2023-02-01T08:25:22.3866667+00:00

    Hello,
    For iOS 10 and later, please see the User notification framework guide. (The doc is about Xamarin, it applies to MAUI)

    First, Notification permission should be requested in the FinishedLaunching method of the AppDelegate and setting the desired notification type (UNAuthorizationOptions), then set the UserNotificationCenterDelegate. Please see the code snippets in Preparing for Notification Delivery part of the doc.

    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)  
        {  
            if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))  
            {  
                // Request notification permissions from the user  
                UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) => {  
                    // Handle approval  
                });  
                UNUserNotificationCenter.Current.Delegate = new UserNotificationCenterDelegate(); //set delegate    
            }  
            return base.FinishedLaunching(application, launchOptions);  
        }
    

    Second, you can add UserNotificationCenterDelegate to handle the foreground App notifications, please see the code snippets in the Handling Foreground App Notifications part of the doc.

    public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate
    {   
        [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]// pay attention to this line
        public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
        {
            completionHandler(UNNotificationPresentationOptions.Banner);
        }
    }
    
    

    Then you can invoke platform code to send local notification for testing, I add a PushNotificationService, you can refer to the following code:

    public partial class PushNotificationService
        {
            public partial void PushLocalNotification();//Define the cross-platform API, which includes a partial method named PushLocalNotification. The code file for this class must be outside of the 
        }
    

    And call the Add method of the UNUserNotificationCenter object to schedule its display to the user in this PushLocalNotification(). Please see the code snippets in Scheduling When a Notification is Sent part of the doc.

    namespace iOSNotoficationSample.Services//the same namespace as PushNotificationService
    {
        public partial class PushNotificationService
        {
            public partial void PushLocalNotification()//implement the API on iOS platform.
            {
                var content = new UNMutableNotificationContent();
                ...//code snippets
                });
            }
        }
    }
    
    

    After that, you can call the PushLocalNotification method in MAUI

    private void OnCounterClicked(object sender, EventArgs e)  
        {// click the button on MainPage to send a local notification for testing 
    #if IOS 
            PushNotificationService pushNotificationService = new PushNotificationService();  
            pushNotificationService.PushLocalNotification();  
    #endif
        }  
    

    Besides, you can try Working with Notification Action

    In addition, this solution is for Local Notification as described in the title if this thread. I saw you set "aps" in the code snippets, you may need Remote Notification. If so, you can create a new thread for Remote Notification. If you have any other issues, please feel free to post in here.

    Best Regards,

    Wenyan Zhang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful