Xamarin Form: iOS 如何模拟后台获取过期

Xamarin Form: iOS how to simulate background fetch expired

我可以使用 iOS 模拟器模拟后台提取。是否可以模拟过期以便调用过期处理程序?我试着用 无限循环和 运行 作为模拟器上的后台获取,但似乎没有触发它。

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);
            });

这是我的一个应用程序的示例:

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...");
}
  • 开始调试您的应用程序

  • 将其置于后台

    • 通过主页按钮,在物理设备上或在模拟设备上Hardware/Home
  • 通过 IDE 中的 Run / Simulate iOS Background Fetch 调用后台提取。

到期处理程序应在大约 30 秒后调用。您有 几秒钟 来处理任何 cleanup/logging。