Search code examples
xamarin.iosgeolocationlocalnotificationxamarin-forms-4

Xamarin IOS - Show local notification when application is closed


I have a Xamarin IOS application that get's the users location each 10 sec, even when the app is killed. I make us of this library: "https://jamesmontemagno.github.io/GeolocatorPlugin/".

What I want is: When the app is closed or open and the user is at a specific location, I want to show a local notification. Is that even possible when the app is closed? I can't find information on this because it's always about remote notifications.


Solution

  • Notification permission should be requested as soon as the app launches by adding the following code to the FinishedLaunching method of the AppDelegate and setting the desired notification type (UNAuthorizationOptions):

    ...
    using UserNotifications;
    ...
    
    
    
     public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
       {
           ....
               
            //after iOS 10
            if(UIDevice.CurrentDevice.CheckSystemVersion(10,0))
            {
                UNUserNotificationCenter center = UNUserNotificationCenter.Current;
    
                center.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.UNAuthorizationOptions.Badge, (bool arg1, NSError arg2) =>
                     {
    
                     });
    
                center.Delegate = new NotificationDelegate();
            }
    
            else if(UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
            {
    
                var settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert| UIUserNotificationType.Badge| UIUserNotificationType.Sound,new NSSet());
    
                UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
    
            }
    
            return true;
        }
    

    New to iOS 10, an app can handle Notifications differently when it is in the foreground and a Notification is triggered. By providing a UNUserNotificationCenterDelegate and implementing the UserNotificationCentermethod, the app can take over responsibility for displaying the Notification. For example:

    using System;
    using ObjCRuntime;
    using UserNotifications;
    
    
    namespace workplat
    {
     public class NotificationDelegate:UNUserNotificationCenterDelegate
       {
        public NotificationDelegate()
        {
        }
    
        public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
        {
            // Do something with the notification
            Console.WriteLine("Active Notification: {0}", notification);
    
            // Tell system to display the notification anyway or use
            // `None` to say we have handled the display locally.
            completionHandler(UNNotificationPresentationOptions.Alert|UNNotificationPresentationOptions.Sound);
        }
    
    
        public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
        {
            // Take action based on Action ID
            switch (response.ActionIdentifier)
            {
                case "reply":
                    // Do something
                    break;
                default:
                    // Take action based on identifier
                    if (response.IsDefaultAction)
                    {
                        // Handle default action...
                    }
                    else if (response.IsDismissAction)
                    {
                        // Handle dismiss action
                    }
                    break;
            }
    
            // Inform caller it has been handled
            completionHandler();
        }
    
      }
    }
    

    To create and register a Custom Action with the system, use the following code:

     public void RegisterNotification(long time)
        {
            UNUserNotificationCenter center = UNUserNotificationCenter.Current;
    
            //creat a UNMutableNotificationContent which contains your notification content
            UNMutableNotificationContent notificationContent = new UNMutableNotificationContent();
    
            notificationContent.Title = "xxx";
            notificationContent.Body= "xxxx";
    
            notificationContent.Sound = UNNotificationSound.Default;
    
            UNTimeIntervalNotificationTrigger trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(time, false);
    
            UNNotificationRequest request = UNNotificationRequest.FromIdentifier("FiveSecond", notificationContent, trigger);
    
    
            center.AddNotificationRequest(request,(NSError obj) => 
            {
               
    
    
            });
    
        }
    

    When you call this method ,for emample:

    RegisterNotification(20);//set the time you want to push notification
    

    The notification will been pushed after 20 seconds,enen if you close your app. You could put this line after uploading the location .

    I have upload my demo to my github, you can download it for your reference: Demo Link .

    And you can access the link for more information and details: MicroSoft Document