0
votes

I am using the CrossGeolocator.Current.StartListeningAsync method in my xamarin app to be able to listen to location updates in background for iOS.

I am using essentials to request permissions.

On first run we get location permission (in app only) and location using essentials and then we use StartListeningAsync for ios to be able to track location if the app is in background or foreground.

When the callback is hit we get a popup saying this app uses background location and gives you the option to use it or change back to use in app only option. On selection of any option the callback never completes and subsequent code isnt run.

Here is the popup I get after I have permission for when in use and then start listening:

Popup on ios

On subsequent runs once permissions are set manually the callback works.

Xamarin Forms Version: 5.0.0.1931 Xamarin Essential Version: 1.6.1 Geolocator Plugin Version: 4.6.2-beta Code example:

    private async Task StartListening()
    {
        if (CrossGeolocator.Current.IsListening)
            return;

        try
        {
            var settings = new ListenerSettings
            {
                ActivityType = ActivityType.Other,
                DeferLocationUpdates = true,
                DeferralDistanceMeters = 15,
                DeferralTime = TimeSpan.FromSeconds(10),
                ListenForSignificantChanges = false,
                PauseLocationUpdatesAutomatically = false,
                AllowBackgroundUpdates = true,
            };
            
            await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(15), 5, true, settings);
            
            CrossGeolocator.Current.PositionChanged += PositionChanged;
            CrossGeolocator.Current.PositionError += PositionError;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
1
Hi, you need to ask permission before starting to listen to location updates. If the permission is well, then invoke StartListening method.Junior Jiang

1 Answers

0
votes

You need to make sure the permission is ok before starting to listen to location updates. Have a try with following code:

public async Task GetLocationAsync()
{
    var status = await CheckAndRequestPermissionAsync(new Permissions.LocationAlways());
    if (status != PermissionStatus.Granted)
    {
        // Notify user permission was denied
        return;
    }else{
        await StartListening();
    }
}

public async Task<PermissionStatus> CheckAndRequestPermissionAsync<T>(T permission)
            where T : BasePermission
{
    var status = await permission.CheckStatusAsync();
    if (status != PermissionStatus.Granted)
    {
        status = await permission.RequestAsync();
    }

    return status;
}