Xamarin.forms 无法在应用程序启动期间访问UIApplication.SharedApplication.KeyWindow,因为KeyWindow始终为空
当我的应用程序启动时,我会像启动屏幕一样显示带有图像的故事板。 然后我从AppDelegate类中的FinishedLaunching()方法调用LoadApplication(new App())。 在我的App.cs中,我需要访问UIApplication.SharedApplication.KeyWindow.RootViewController以显示进度条。 但Keywindow为null,因此存在崩溃Xamarin.forms 无法在应用程序启动期间访问UIApplication.SharedApplication.KeyWindow,因为KeyWindow始终为空,xamarin.forms,xamarin.ios,uiwindow,uiapplication,keywindow,Xamarin.forms,Xamarin.ios,Uiwindow,Uiapplication,Keywindow,当我的应用程序启动时,我会像启动屏幕一样显示带有图像的故事板。 然后我从AppDelegate类中的FinishedLaunching()方法调用LoadApplication(new App())。 在我的App.cs中,我需要访问UIApplication.SharedApplication.KeyWindow.RootViewController以显示进度条。 但Keywindow为null,因此存在崩溃 public override bool FinishedLaunching(UIA
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
DependencyService.Register<ILoadingService,LoadingService>();
global::Xamarin.Forms.Forms.Init();
Xamarin.FormsGoogleMaps.Init("AIzaSyCqt-tfGrKhauCgC2Y5UkPreXfMZisPOH8");
LoadApplication(new App());
UIWindow.Appearance.TintColor = new UIColor(red: 0.55f, green: 0.76f, blue: 0.29f, alpha: 1.0f);
return base.FinishedLaunching(app, options);
}
这里的Keywindow为空。
有什么建议我做错了什么吗?原因: 此时,
keyWindow
尚未实例化
解决方案:
您可以将show
功能置于OnStart
下
protected override void OnStart()
{
// Handle when your app starts
DependencyService.Get<ILoadingService>().Show("Updating user token...");
}
protectedoverride void OnStart()
{
//在应用程序启动时处理
DependencyService.Get().Show(“正在更新用户令牌…”);
}
请参阅:UIWindow窗口=新UIWindow(UIScreen.MainScreen.Bounds);UINavigationController navController=新的UINavigationController();window.RootViewController=navController;window.MakeKeyAndVisible();我在AppDelegate的FinishedLaunching()方法中添加了此代码。它现在可以工作了,但将来会有什么问题吗@杰克Hua@SaiSunkari将来它不会破坏任何东西。当应用程序已加载并准备运行时,将调用此方法。您可以使用此方法自定义
窗口
和RootViewController
。如果不在此方法中实例化它们,默认情况下窗口将实例化,RootViewController
将是App.cs
中的MainPag
。
public void Show(string title, string message = "Loading")
{
UIViewController controller =
UIApplication.SharedApplication.KeyWindow.RootViewController;
hud = new MTMBProgressHUD(controller.View);
controller.View.AddSubview(hud);
}
protected override void OnStart()
{
// Handle when your app starts
DependencyService.Get<ILoadingService>().Show("Updating user token...");
}