Rutger Huijsmans
Rutger Huijsmans

Reputation: 2408

Determining class of the rootViewController

I'm trying to determine the class of the rootViewController because I do not want push notifications to show up on all of the screens. However the following line keeps getting validated as true on every view of my project:

print(UIApplication.sharedApplication().keyWindow?.rootViewController!.isKindOfClass(TabView))

To further examine the problem I've added titles to all the views on Storyboard. After doing this I tried to print the titles of the current screen that shown on the iPhone/Simulator. However, a title different from what I was expecting gets printed:

UIApplication.sharedApplication().keyWindow?.rootViewController!.title

Upvotes: 0

Views: 142

Answers (1)

Joseph Afework
Joseph Afework

Reputation: 269

When you display modal View Controllers the rootViewController on the window is unaffected. It is still set to whatever the original rootViewController is

Consider the following:

let tabController = TabView()
self.window.rootViewController = tabController

let modalController = UINavigationController()
self.window.rootViewController.presentModalViewController(modalController,animated:false completion:nil)

self.window.rootViewControler is unchanged, and if you check the class of it, you will see that it will ALWAYS match the TabView

What you want to do is to actually get the topmost VISIBLE view controller.

To do this you need to get the rootViewController, and check to see if it has modally displayed any view controllers, and keep following it recursively until you can't find another controller. Once you have the topmost view controller, check its class to see if it matches TabView like you are doing.

see https://stackoverflow.com/a/29817515/4761517 for an example implementation of how to find the topmost viewcontroller.

Upvotes: 2

Related Questions