Unable to get RootViewController in Xamarin iOS

2019-07-18 10:00发布

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

4条回答
成全新的幸福
2楼-- · 2019-07-18 10:25

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楼-- · 2019-07-18 10:27

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楼-- · 2019-07-18 10:41

This looks stupid but works.

        UIWindow window = UIApplication.SharedApplication.KeyWindow;
        UIViewController presentedVC = window.RootViewController;
        while (presentedVC.PresentedViewController != null)
        {
            presentedVC = presentedVC.PresentedViewController;
        }
查看更多
在下西门庆
5楼-- · 2019-07-18 10:45

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; 
        }
    }
查看更多
登录 后发表回答