Unable to get RootViewController in Xamarin iOS

2019-07-18 10:44发布

问题:

I created app, which Authenticate using Azure AD

In Android it is working fine, but in iOS, it need RootViewController for load the page. But UIApplication.SharedApplication.KeyWindow is null. So I am not able to get UIApplication.SharedApplication.KeyWindow.RootViewController

Bellow is the code:

var authResult = await authContext.AcquireTokenAsync(
    graphResourceUri, 
    ApplicationID, 
    new Uri(returnUri), 
    new PlatformParameters(UIApplication.SharedApplication.KeyWindow.RootViewController)
);

Any other way from which I can get RootViewController

回答1:

This looks stupid but works.

        UIWindow window = UIApplication.SharedApplication.KeyWindow;
        UIViewController presentedVC = window.RootViewController;
        while (presentedVC.PresentedViewController != null)
        {
            presentedVC = presentedVC.PresentedViewController;
        }


回答2:

I tried this code also, but it is not working.

I got the root cause of this issue. Issue was, when I am going to access the RootViewController then there should be at least one page Initialized, but it is not Initialized so I am unable to get RootViewController

so I gave daily to Initialized the page then I got the RootViewController



回答3:

Access RootViewController after your window is actually created. Do this after base.FinishedLauching, like this:

var result = base.FinishedLaunching(app, options);
var platformParameters = UIApplication.SharedApplication.KeyWindow.RootViewController;
App.AuthenticationClient.PlatformParameters = new PlatformParameters(platformParameters);
return result;


回答4:

Depending on the type of window you have loaded getting the RootViewController can be problematic. This version has been the most stable one I've tried thus far and avoids tail recursive loops.

    public UIViewController GetRootController(){
        var root = UIApplication.SharedApplication.KeyWindow.RootViewController;
        while (true)
        {
            switch (root)
            {
                case UINavigationController navigationController:
                    root = navigationController.VisibleViewController;
                    continue;
                case UITabBarController uiTabBarController:
                    root = uiTabBarController.SelectedViewController;
                    continue;
            }

            if (root.PresentedViewController == null) return root;
            root = root.PresentedViewController; 
        }
    }