Search code examples
xamarin.formsxamarin.androidxamarin.iosbackground-processandroidx

Is there PeriodicWorkRequest equivalent for iOS to use in background?


We are working on Xamarin.Forms app.
One of the mechanisms we need to do is to upload a bunch of images in the background, and in case of failure retry until it works.

For Android, it is quite straightforward:

using AndroidX.Work;
...
        PeriodicWorkRequest uploadWorkRequest = PeriodicWorkRequest.Builder.From<UploadWorker>(TimeSpan.FromMinutes(20)).Build();
        WorkManager.Instance.Enqueue(uploadWorkRequest);

where

public class UploadWorker : Worker
{
    public UploadWorker(Context context, WorkerParameters workerParameters) : base(context, workerParameters) { }

    public override Result DoWork()
    {
 //do your stuff
    }
}

Now obviously this mechanism is not present for iOS, but the functionality to run a task in the background and repeat if it fails should be there.

Is there PeriodicWorkRequest equivalent for iOS?


Solution

  • In iOS we could use NSTimer to implement some repeating tasks .

    _timer = NSTimer.CreateRepeatingScheduledTimer(TimeSpan.FromSeconds(20), () =>
    {
        this.InvokeOnMainThread(()=>{
            //Your code goes here
        });
    }
    

    Start the timer

    timer.Fire();
    

    Stop the timer (invoke it when leaving the current ViewController)

    _timer.Invalidate();