Forum Xamarin Xamarin.Forms

Keeps background service up when the user swipes out (close) the application Xamarin Forms iOS

Hello,
I have developed a Xamarin Forms app that updates location every x seconds in a background service; the application works great in Android and iOS, but I still need to figure out how to keep the service alive when the user swipes out/close the application on iPhone.
This is how my iOS class service looks:

public class iOSLocationUpdate
{
nint _taskId;
CancellationTokenSource _cts;

    public async Task Start()
    {
        _cts = new CancellationTokenSource();
        _taskId = UIApplication.SharedApplication.BeginBackgroundTask("com.iPhocus.iLinkWireless.update", OnExpiration);

        try
        {
            //INVOKE THE SHARED CODE
            var counter = new UpdateLocation();
            await counter.RunLocation(_cts.Token);

        }
        catch (OperationCanceledException)
        {
        }
        finally
        {
            if (_cts.IsCancellationRequested)
            {
                var message = new CancelledMessage();
                Device.BeginInvokeOnMainThread(
                    () => MessagingCenter.Send(message, "CancelledLocation")
                );
            }
        }

        var time = UIApplication.SharedApplication.BackgroundTimeRemaining;

        UIApplication.SharedApplication.EndBackgroundTask(_taskId);
    }

    public void Stop()
    {
        _cts.Cancel();
    }

    void OnExpiration()
    {
        UIApplication.SharedApplication.EndBackgroundTask(_taskId);
    }
}

This is the content of my AppDelegate:
iOSLocationUpdate locationUpdate;
CLLocationManager locMgr = new CLLocationManager();
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
Rg.Plugins.Popup.Popup.Init();
global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental");
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
locationUpdate = new iOSLocationUpdate();
UIApplication.SharedApplication.SetMinimumBackgroundFetchInterval(UIApplication.BackgroundFetchIntervalMinimum);

        //Background Location Permissions
        if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
        {
            locMgr.RequestAlwaysAuthorization();
        }

        if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
        {
            locMgr.AllowsBackgroundLocationUpdates = true;
        }

        WireUpLocationTask();

        return base.FinishedLaunching(app, options);
    }

    void WireUpLocationTask()
    {
        MessagingCenter.Subscribe<StartLocationUpdateMessage>(this, "StartLocationUpdateMessage", async message => {
            await locationUpdate.Start();
        });

        MessagingCenter.Subscribe<StopLocationUpdateMessage>(this, "StopLocationUpdateMessage", message => {
            locationUpdate.Stop();
        });
    }

My info.list:
UIBackgroundModes

location
fetch
processing

BGTaskSchedulerPermittedIdentifiers
NSLocationWhenInUseUsageDescription
These permissions are needed to give get the most accurate location of your device.
NSLocationAlwaysUsageDescription
These permissions are needed to give get the most accurate location of your device.
CFBundleShortVersionString
0.3

The full code of the app can be downloaded on:

github.com/shernandezp/XamarinForms.LocationService

I appreciate any suggestions,

Thanks.

Answers

Sign In or Register to comment.