unable to access UIApplication.SharedApplication.KeyWindow during the launch of the app as keywindow is always null

2.1k Views Asked by At

When my app is launched i show the Storyboad with an image in it like a splash screen. Then i call LoadApplication(new App()) from FinishedLaunching() method in AppDelegate class. In my App.cs, I need to access UIApplication.SharedApplication.KeyWindow.RootViewController to show a progress bar. But Keywindow is null and hence there is crash.

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

App.cs file:

public App(string ticketNumberNotifParam = null, int ticketID = 0)
{
DependencyService.Get<ILoadingService>().Show("Updating user token...");
LoadHomepage();
}

LoadingService();

public void Show(string title, string message = "Loading")
{
UIViewController controller = 
UIApplication.SharedApplication.KeyWindow.RootViewController;
        hud = new MTMBProgressHUD(controller.View);
        controller.View.AddSubview(hud);
}

Here Keywindow is null. Any suggestions what I'm doing wrong?

1

There are 1 best solutions below

2
nevermore On

Cause:

The keyWindow hasn't been instantiated at that point.

Solution:

You can put your show function under OnStart.

 protected override void OnStart()
    {
        // Handle when your app starts

        DependencyService.Get<ILoadingService>().Show("Updating user token...");

    }

Refer: app-lifecycle