Xamarin.iOS Is there any way to grab user coordinates in the Notification Service Extension?

Cdn_EuroCdn_Euro Member ✭✭✭
edited January 26 in Xamarin.iOS

I would like as functionality for my app the ability to customize the push notification for the user based on their location at the moment when they receive the push notification.

I tried to access the user's coordinates in the Notification Extension project using Xamarin Essentials but they turned out with the value of 0.
Of course, accessing the user's coordinates works fine in the main project.

How can I achieve this, is it possible?

Answers

  • LandLuLandLu Member, Xamarin Team Xamurai

    Firstly, we need to enable the location service in the container application. So add the following privacy in the container's info.plist:

    NSLocationAlwaysAndWhenInUseUsageDescription
    NSLocationWhenInUseUsageDescription
    

    Then call the Xamarin.Essentials or use dependency service to request the location permission on iOS. However, Apple replace the always allow permission to allow once on iOS 13 it means we could only let the user choose "while using app" permission now. And this setting is adapted to the extension. When we consume the location service in extension the app must be in foreground:

    public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler)
    {
        ContentHandler = contentHandler;
        BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy();
        // Modify the notification content here...
    
        CLLocationManager manager = new CLLocationManager();
        BestAttemptContent.Body = “latitude” + manager.Location.Coordinate.Latitude;
        ContentHandler(BestAttemptContent);
    }
    

    This setting could be changed by the user in the setting application or trying to request a background location service in the container app:
    http://info.localytics.com/blog/what-you-need-to-know-about-the-new-ios-13-location-permissions

  • Cdn_EuroCdn_Euro Member ✭✭✭

    @LandLu Thank you, will try that. So you are saying that Geolocation should work in the Extension too? I have the impression that the Extension can't access the GPS and other phone hardware...

  • LandLuLandLu Member, Xamarin Team Xamurai

    Yes, I have tried that. The location service runs fine in the extension.

Sign In or Register to comment.