Search code examples
c#.netxamarinxamarin.iosmaui

Get the current ViewController in .NET MAUI


I am porting a Xamarin Forms code into .NET MAUI, but the code I have there to get the current view controller does not work, how do I get the current ViewControler in MAUI

Relevant code here: Using UIDocumentPickerViewController in Xamarin forms as a dependency service

Relevant Xamarin Forms(iOS) code:

public UIViewController GetCurrentUIController()
{
    UIViewController viewController;
    var window = UIApplication.SharedApplication.KeyWindow;
    if (window == null)
    {
        return null;
    }

    if (window.RootViewController.PresentedViewController == null)
    {
        window = UIApplication.SharedApplication.Windows
                 .First(i => i.RootViewController != null &&
                             i.RootViewController.GetType().FullName
                             .Contains(typeof(Xamarin.Forms.Platform.iOS.Platform).FullName));
    }

    viewController = window.RootViewController;

    while (viewController.PresentedViewController != null)
    {
        viewController = viewController.PresentedViewController;
    }

    return viewController;
}

Solution

  • After spending a good amount of time porting this code, I realised that the relevant namespaces that were available in Xamarin Forms are now either internal or not there anymore, so I spent some time searching on what's the right way to do this with MAUI which again I did not find, but after some snooping into this Microsoft documentation I realised that the ApplicationModel's Platform class has exactly what I need,

    var currentViewController = Microsoft.Maui.ApplicationModel.Platform.GetCurrentUIViewController();
    

    Adding this here so someone else does not have a waste an hour or two on this simple thing :)