我正在使用 Xamarin.Forms 版本 5.0.0.2662 和用于定期作业的 Shiny 库(版本 2.7.3)开发一个应用程序。定期作业在 Android 设备上完美运行,但在 iOS 设备上不起作用。相反,我收到以下错误消息:
ex {System.InvalidOperationException: ServiceProvider is not initialized - This means you have not setup Shiny correctly! Please follow instructions at https://shinylib.net at Shiny.ShinyHost.get_ServiceProvider () [0x00007] in <c4b34a60966e4f8a972a9ce9769e4433…}
iOS配置
以下是我配置 iOS AppDelegate 的方法:
[assembly: Shiny.ShinyApplication(
ShinyStartupTypeName = "AppData.System.Startup",
XamarinFormsAppTypeName = "AppData.System.App"
)]
namespace AppData.System.iOS
{
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
try
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
}
catch (System.Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
return base.FinishedLaunching(app, options);
}
public override void PerformFetch(UIApplication application, Action<UIBackgroundFetchResult> completionHandler)
{
ShinyHost.Resolve<IJobManager>()
.RunAll()
.ContinueWith(task =>
{
if (task.IsCompletedSuccessfully)
completionHandler(UIBackgroundFetchResult.NewData);
else
completionHandler(UIBackgroundFetchResult.Failed);
});
}
}
}
Xamarin.Forms 启动
我的Xamarin.Forms项目中的启动配置如下:
namespace AppData.SystemUsers
{
public class Startup : ShinyStartup
{
public override void ConfigureServices(IServiceCollection services, IPlatform platform)
{
services.UseJobs(true);
services.UseNotifications();
services.RegisterJob(new JobInfo(typeof(SyncJob), "SyncJobs")
{
Repeat = true,
BatteryNotLow = false,
DeviceCharging = false,
RunOnForeground = true,
RequiredInternetAccess = InternetAccess.Any
});
}
}
}
工作落实
这就是我工作的执行。在 Android 上,它通过 POST 请求成功向 API 发送消息。然而,在 iOS 上,它会失败并出现上述错误:
public class SyncJobs : IJob
{
private readonly INotificationManager notificationManager;
private static bool IsRunning = false;
public SyncJobs(INotificationManager notificationManager)
=> this.notificationManager = notificationManager;
public async Task Run(JobInfo jobInfo, CancellationToken cancelToken)
{
if (!IsRunning)
{
IsRunning = true;
await APIServices.SendPostMessage(cancelToken, $"Init - iPhone");
IsRunning = false;
}
}
}
信息.plist
<plist version="1.0">
<dict>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>processing</string>
<string>remote-notification</string>
</array>
</dict>
</plist>
在App.xaml中执行
在App.xaml中,我强制执行作业,这就是发生异常的地方:
Shiny.ShinyHost.Resolve<Shiny.Jobs.IJobManager>().Run("SyncJobs");
有谁知道为什么 iOS 上服务提供商初始化失败以及如何解决此问题?我已经尝试按照 Shiny 库设置说明进行操作,但似乎无法弄清楚 iOS 缺少什么。 我正在真实设备上测试,而不是在模拟器上。
我设法在 AppDelegate -> FinishedLaunching 中解决了这个问题。 我在一开始就添加了这段代码,它起作用了:
this.ShinyFinishedLaunching(new Startup());