iosxamarinbackground-fetchexpirationhandler

Xamarin Form: iOS how to simulate background fetch expired


I can simulate the background fetch using iOS simulator. Is it possible to simulate the expiration so it can call the expire handler? I tried to use a infinite loop and run as background fetch on an simulator but doesn't seem to trigger it.

task = UIApplication.SharedApplication.BeginBackgroundTask("bgEntityDownload", () =>
            {
                AppLogger.Instance.AddLog(AppLogLevel.Information,
                                      nameof(BgProcess),
                                      nameof(DownloadEntityFromServer),
                                      "Background Fetch Expired", "");
                App.CurrentDataStatus.HasSync = new EntityQueueBLL().HasData(siteId);
                UIApplication.SharedApplication.EndBackgroundTask(task);
                task = UIApplication.BackgroundTaskInvalid;
                System.Diagnostics.Debug.WriteLine("Ending .....");
                completionHandler?.Invoke(UIBackgroundFetchResult.NewData);
            });

Solution

  • Here is a sample out of one of my apps:

    public async override void PerformFetch(UIApplication application, Action<UIBackgroundFetchResult> completionHandler)
    {
        var result = UIBackgroundFetchResult.NoData;
        try
        {
            await Task.Run(async () =>
            {
                var iOSTaskId = UIApplication.SharedApplication.BeginBackgroundTask("MyBackgroundTask", ExpirationHandler);
                //result = await BackgroundFetchBoxOfficeTicketResults();
                await Task.Delay(60 * 1000);
                result = UIBackgroundFetchResult.NewData;
                UIApplication.SharedApplication.EndBackgroundTask(iOSTaskId);
            });
        }
        catch // Fetch Errors are Reported via analytics system within BackgroundFetchBoxOfficeTicketResults
        {
            result = UIBackgroundFetchResult.Failed;
        }
        completionHandler(result);
    }
    
    void ExpirationHandler()
    {
        //Report(ProgID, PerFormFetchFailedID, DeviceID, $"User:{UserID}, Network:{NetworkType}");
        Console.WriteLine("beginBackgroundTaskWithName:expirationHandler: called...");
    }
    

    The expiration handler should be invoked about 30 seconds later. You have a few seconds to handle any cleanup/logging.