Xamarin – Local notification for iOS (1)

How to create a local notification?

Add permission check

App.xaml.cs

        public App()
        {
            ...
            DependencyService.Get<INotificationManager>().Initialize();
            ...
        }

iOSNotificationManager.cs

[assembly: Dependency(typeof(localnotification.iOS.iOSNotificationManager))]
namespace localnotification.iOS
{
    public class iOSNotificationManager : INotificationManager
    {
        ...
        public void Initialize()
        {
            // request the permission to use local notifications
            UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert, (approved, err) =>
            {
                hasNotificationsPermission = approved;
            });
        }
        ...
    }

Send notification

  • Use UNTimeIntervalNotificationTrigger to create a local notification immediately
  • Use UNCalendarNotificationTrigger to create a local notification at an exact time
    public partial class MainPage : ContentPage
    {
        ...

        private void SendNotification(object sender, EventArgs e)
        {
            DependencyService.Get<INotificationManager>().SendNotification("Title", "Message");
        }

        ...
    ...
    public class iOSNotificationManager : INotificationManager
    {
        int messageId = 0;
        bool hasNotificationsPermission;
        public event EventHandler NotificationReceived;

        ...

        public void SendNotification(string title, string message, DateTime? notifyTime = null)
        {
            // EARLY OUT: app doesn't have permissions
            if (!hasNotificationsPermission)
            {
                return;
            }

            messageId++;

            var content = new UNMutableNotificationContent()
            {
                Title = title,
                Subtitle = "",
                Body = message,
                Badge = 1
            };

            UNNotificationTrigger trigger;
            if (notifyTime != null)
            {
                // Create a calendar-based trigger.
                trigger = UNCalendarNotificationTrigger.CreateTrigger(GetNSDateComponents(notifyTime.Value), false);
            }
            else
            {
                // Create a time-based trigger, interval is in seconds and must be greater than 0.
                trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(0.25, false);
            }

            var request = UNNotificationRequest.FromIdentifier(messageId.ToString(), content, trigger);
            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    throw new Exception($"Failed to schedule notification: {err}");
                }
            });
        }

        public void ReceiveNotification(string title, string message)
        {
            var args = new NotificationEventArgs()
            {
                Title = title,
                Message = message
            };
            NotificationReceived?.Invoke(null, args);
        }

        NSDateComponents GetNSDateComponents(DateTime dateTime)
        {
            return new NSDateComponents
            {
                Month = dateTime.Month,
                Day = dateTime.Day,
                Year = dateTime.Year,
                Hour = dateTime.Hour,
                Minute = dateTime.Minute,
                Second = dateTime.Second
            };
        }
    }

Receive notification

    public class iOSNotificationReceiver: UNUserNotificationCenterDelegate
    {
        // Called if app is in the foreground.
        public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
        {
            ProcessNotification(notification);
            completionHandler(UNNotificationPresentationOptions.Alert);
        }

        // Called if app is in the background, or killed state.
        public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
        {
            if (response.IsDefaultAction)
            {
                ProcessNotification(response.Notification);
            }
            completionHandler();
        }

        void ProcessNotification(UNNotification notification)
        {
            string title = notification.Request.Content.Title;
            string message = notification.Request.Content.Body;

            DependencyService.Get<INotificationManager>().ReceiveNotification(title, message);
        }
    }

Handle incoming notification

AppDelegate.cs

namespace localnotification.iOS
{
        ...
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            ...

            // Set a delegate to handle incoming notifications.
            UNUserNotificationCenter.Current.Delegate = new iOSNotificationReceiver();

            ...
            return base.FinishedLaunching(app, options);
        }
    }
}

How to create a schedule notification?

private void SendScheduleNotification(object sender, EventArgs e)
{
     DependencyService.Get<INotificationManager>().SendNotification("title", "content", DateTime.Now.AddSeconds(10));
}

How to create a repeat daily notification?

Every Thursday, 3:02 pm

// Calendar trigger
var trigger = UNCalendarNotificationTrigger.CreateTrigger(new NSDateComponents() { Weekday = 5, Hour = 15, Minute = 02 }, true);

Be the first to comment

Leave a Reply

Your email address will not be published.


*