0

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?

Sai Sunkari
  • 179
  • 3
  • 27

1 Answers1

1

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

nevermore
  • 15,432
  • 1
  • 12
  • 30
  • UIWindow window = new UIWindow(UIScreen.MainScreen.Bounds); UINavigationController navController = new UINavigationController(); window.RootViewController = navController; window.MakeKeyAndVisible(); I added this code in AppDelegate's FinishedLaunching() methos. Its working now but does this breaks anything in future? @Jack Hua – Sai Sunkari Jan 24 '19 at 19:46
  • 1
    @SaiSunkari It won't break anything in future. This method is invoked when the application has loaded and is ready to run. You can customize the `window` and `RootViewController` in this method. If you doesn't instantiate them in this method, the window will instantiate by default, and the `RootViewController` would be the `MainPag` in `App.cs`. – nevermore Jan 25 '19 at 01:36