Search code examples
xamarin.formsxamarin.iosprismapplication-lifecycle

Xamarin.Forms.Application.Current.MainPage is null


I have unusual case scenario where I am migrating the app from iOS to Forms.

My setups are -

  1. iOS project loading signing UIViewController and handelling login routine. MainPage is null.

  2. On Login routine finished I load XF view as UIViewController and add it to navigation Stack

var formsController = formsPage.CreateViewController();

CoreApplication.Instance.FormsController = formsController;

var CurrentNavigationController = UIApplication.SharedApplication.KeyWindow.RootViewController;

var viewControllersStack = CurrentNavigationController.ChildViewControllers;

viewControllersStack[viewControllersStack.Length - 1].NavigationController.PushViewController(CoreApplication.Instance.FormsController, true);

Thats when MainPage has value as Navigation set it to navigated page.

  1. I move to background.
protected override void OnSleep()
{
    if (Application.Current.MainPage != null)
    {
        Console.WriteLine("!!!! ---  " + Application.Current.MainPage.GetType().Name);
    }
}

I am getting name of MainPage - so value is not null.

  1. I am getting back to foreground => OnResume() catches that MainPage is null.

But I am getting back to my XF view. Navigation is working between the pages and everything seems fine.

The only problem now since MainPage is null now - some of the libraries like Rg.Plugins.Popup are not working since they are having references to MainPage and I am getting crashes.

Any help/idea of how I can keep references of MainPage alive?

thank you!

PS

I did some investigation if I call NavigationService.NavigateAsync(MyPage); from App.xaml.cs or do=> MainPage = new MyPage(); Then instance of MainPage keeps alive through all app life cycles.


Solution

  • As can se from the comments to original post - the resolve of the issue was to move app logic when XF becomes first responder on app startup. Then I am managing navigation as normal and when required to load UIViecontrollers - getting UIApplication.SharedApplication.KeyWindow to Present ViewController.

    More details on how to do that can be found here