pableiros
pableiros

Reputation: 16062

How to get rootViewController in iOS 13 using Objective-C?

I'm trying to get the rootViewController in iOS 13 using Objective-C. I'm doing something like this:

for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {
    UIWindowScene *windowScene = (UIWindowScene *) scene;
    UIWindowSceneDelegate *windowSceneDelegate = (UIWindowSceneDelegate *) windowScene.delegate;
    windowSceneDelegate.window = ...
}

But when I try to access the window property in windowSceneDelegate.window = (to get the rootViewController) I get the following error:

Property 'window' cannot be found in forward class object 'UIWindowSceneDelegate'

But when I go to the definition of UIWindowSceneDelegate, I see a window property:

enter image description here

So what is the right way get rootViewController in iOS 13 using Objective-C?

Upvotes: 1

Views: 1508

Answers (1)

zrzka
zrzka

Reputation: 21249

Change your code to:

for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {
    if ([scene.delegate conformsToProtocol:@protocol(UIWindowSceneDelegate)]) {
        UIWindow *window = [(id<UIWindowSceneDelegate>)scene.delegate window];
    }
}

When you open the UIKits UIWindowScene.h header file, it contains:

@class UIScreen, UIWindow, UIWindowSceneDelegate, UISceneDestructionRequestOptions, CKShareMetadata, UISceneSizeRestrictions;

See, there's the UIWindowSceneDelegate. This is the forward declaration.

Read this answer to learn what the forward declaration is.

Upvotes: 4

Related Questions