Forum Xamarin.iOS

Xamarin Forms ios - Continuous task to work for hours even app in the background

My requirement is to send the location of the device to the rest api continuously for every 30 seconds.
I have used UIApplication.SharedApplication.BeginBackgroundTask to make it work even the app went to the background, but IOS is suspending the app after 3 minutes.
Is it possible to continuously allow the app to work in the background for hours?

Best Answer

  • edited February 2019 Accepted Answer

    This below code is working fine for my requirement.

    Send the function you want to execute to this method as action and it will run continuously.
    Insert a delay at the end of the function to make it run in the time intervals you want.

    private static nint interger = -1;
            public async Task RunCodeInBackground(Func<Task> action, string name = "MyBackgroundTaskName")
                CancellationTokenSource cxl = new CancellationTokenSource();
                nint newtaskId = UIApplication.SharedApplication.BeginBackgroundTask("Long-Running Task", () =>
                    nint insideTask = interger;
                    if (insideTask != -1 && UIApplication.SharedApplication.BackgroundTimeRemaining < 30)
                        insideTask = UIApplication.BackgroundTaskInvalid;
                interger = newtaskId;
                    await Task.Run(async () =>
                        await action();
                    }, cxl.Token);
                catch (Exception)
                    await RunCodeInBackground(action);            


Sign In or Register to comment.