85

As far as I know, this would work in Objective-C:

self.window.rootViewController.class == myViewController

How can I check if the current view controller is a specific one?

1
  • Are you trying to determine if it's an instance of a particular class, or a specific instance?
    – mc01
    Dec 31, 2014 at 3:53

18 Answers 18

98

To check the class in Swift, use "is" (as explained under "checking Type" in the chapter called Type Casting in the Swift Programming Guide)

if self.window.rootViewController is MyViewController {
    //do something if it's an instance of that class
}
4
  • 9
    The variable self.window does not exist
    – user83039
    Dec 31, 2014 at 3:58
  • @user83039 What is self in this case then? Where are you putting the code? self.window and rootViewController are in AppDelegate. Need more info.
    – mc01
    Dec 31, 2014 at 4:23
  • I'm inside of a view controller.
    – user83039
    Dec 31, 2014 at 4:29
  • 1
    That's the problem then - viewControllers don't have a window, and any code you put there will only tell you about itself, which isn't helpful. See: stackoverflow.com/questions/20485585/… AND stackoverflow.com/questions/11637709/…
    – mc01
    Dec 31, 2014 at 4:34
50

Updated for swift3 compiler throwing a fit around ! and ?

if let wd = UIApplication.shared.delegate?.window {
        var vc = wd!.rootViewController
        if(vc is UINavigationController){
            vc = (vc as! UINavigationController).visibleViewController

        }

        if(vc is LogInViewController){
            //your code
        }
    }
3
  • 2
    No such thing as self.window
    – user83039
    Jan 1, 2015 at 2:02
  • 1
    are you in AppDelegate? if not, you can get your AppDelegate and do something like that.
    – Nhut Duong
    Jan 5, 2015 at 4:52
  • 3
    Awesome, this worked for me. Just instead of self.window use self.view.window
    – Coltrane
    Aug 24, 2015 at 0:22
32

You can easily iterate over your view controllers if you are using a navigation controller. And then you can check for the particular instance as:
Swift 5

 if let viewControllers = navigationController?.viewControllers {
            for viewController in viewControllers {
                if viewController.isKind(of: LoginViewController.self) {
                    
                }
            }
        }
8
  • 1
    I don't have an object, the current window is supposed to be the object.
    – user83039
    Jan 1, 2015 at 2:26
  • 1
    Use self.isKindOfClass then Jan 1, 2015 at 4:03
  • 1
    self is not necessarily what is being shown if I'm using that function from another class...
    – user83039
    Jan 1, 2015 at 4:11
  • I'm using both actually. The navigation controllers are inside the tab bar controller.
    – user83039
    Jan 1, 2015 at 6:00
  • What if I put this inside of a struct inside of the class?
    – user83039
    Jan 2, 2015 at 0:32
13

I had to find the current viewController in AppDelegate. I used this

//at top of class
var window:UIWindow?

// inside my method/function
if let viewControllers = window?.rootViewController?.childViewControllers {
    for viewController in viewControllers {
        if viewController.isKindOfClass(MyViewControllerClass) {
            println("Found it!!!")
            }
        }
    }
13

Try this

if self is MyViewController {        

}
2
  • 1
    self is not necessarily what is being shown if I'm using a function from another class...
    – user83039
    Jan 1, 2015 at 2:01
  • Thanks, this helped. This is particularly useful for checking the currently presenting viewController. I was able to tell whether the controller was a UIAlertController to prevent multiple presentations.
    – 6rchid
    Aug 19, 2020 at 2:31
8

Swift 3

Not sure about you guys, but I'm having a hard time with this one. I did something like this:

if let window = UIApplication.shared.delegate?.window {
    if var viewController = window?.rootViewController {
        // handle navigation controllers
        if(viewController is UINavigationController){
            viewController = (viewController as! UINavigationController).visibleViewController!
        }
        print(viewController)
    }
}

I kept getting the initial view controller of my app. For some reason it wanted to stay the root view controller no matter what. So I just made a global string type variable currentViewController and set its value myself in each viewDidLoad(). All I needed was to tell which screen I was on & this works perfectly for me.

7

To go off of Thapa's answer, you need to cast to the viewcontroller class before using...

   if let wd = self.view.window {
        var vc = wd.rootViewController!
        if(vc is UINavigationController){
            vc = (vc as! UINavigationController).visibleViewController
        }
        if(vc is customViewController){
            var viewController : customViewController = vc as! customViewController
7

Swift 4, Swift 5

let viewController = UIApplication.shared.keyWindow?.rootViewController
if viewController is MyViewController {

}
1

For types you can use is and if it is your own viewcontroller class then you need to use isKindOfClass like:

let vcOnTop = self.embeddedNav.viewControllers[self.embeddedNav.viewControllers.count-1]
            if vcOnTop.isKindOfClass(VcShowDirections){
                return
            }
1

Swift 3 | Check if a view controller is the root from within itself.

You can access window from within a view controller, you just need to use self.view.window.

Context: I need to update the position of a view and trigger an animation when the device is rotated. I only want to do this if the view controller is active.

class MyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(
            self, 
            selector: #selector(deviceDidRotate), 
            name: .UIApplicationDidChangeStatusBarOrientation, 
            object: nil
        )
    }

    func deviceDidRotate() {
        guard let window = self.view.window else { return }

        // check if self is root view controller
        if window.rootViewController == self {
            print("vc is self")
        }

        // check if root view controller is instance of MyViewController
        if window.rootViewController is MyViewController {
            print("vc is MyViewController")
        }
    }
}

If you rotate your device while MyViewController is active, you will see the above lines print to the console. If MyViewController is not active, you will not see them.

If you're curious why I'm using UIDeviceOrientationDidChange instead of .UIDeviceOrientationDidChange, look at this answer.

1
let viewControllers = navController?.viewControllers
        for aViewController in viewControllers! {

            if aViewController .isKind(of: (MyClass?.classForCoder)!) {
                _ = navController?.popToViewController(aViewController, animated: true)
            }
        }
1

Check that way that worked better for me What is .self

if ((self.window.rootViewController?.isKind(of: WebViewController.self))!)
{
  //code
}
1

After implementing and try is current viewController is open I find 100% solution

for example when receiving a new notification

here the implement using 'userNotificationCenter'

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    
    // Change this to your preferred presentation option
    Messaging.messaging().appDidReceiveMessage(userInfo)
    
    let keyWindow = UIApplication.shared.connectedScenes
        .map({$0 as? UIWindowScene})
        .compactMap({$0})
        .first?.windows
        .filter({$0.isKeyWindow}).first
    
    guard let window = keyWindow else { return }
    
    if window.rootViewController?.children.last is MyViewController{
        print("Chat")
        completionHandler([])
    }else{
        print("Not not not Chat")
        completionHandler([.alert, .badge, .sound])
    }
 }

and simply to check try this

let keyWindow = UIApplication.shared.connectedScenes
        .map({$0 as? UIWindowScene})
        .compactMap({$0})
        .first?.windows
        .filter({$0.isKeyWindow}).first
    
    guard let window = keyWindow else { return }
    
    if window.rootViewController?.children.last is MyViewController{
        print("Yes Its current ViewController")
    }else{
        print("Not it's not Current ViewController")
    }
1

Swift 5 and iOS 15

if self.navigationController?.presentedViewController != nil && 
        self.navigationController?.presentedViewController is ChatViewController {
            return
    }
0
if let index = self.navigationController?.viewControllers.index(where: { $0 is MyViewController }) {
            let vc = self.navigationController?.viewControllers[vcIndex] as! MyViewController
            self.navigationController?.popToViewController(vc, animated: true)
        } else {
            self.navigationController?.popToRootViewController(animated: true)
        }
0

My suggestion is a variation on Kiran's answer above. I used this in a project.

Swift 5

// convenience property API on my class object to provide access to the my WindowController (MyController).
var myXWindowController: MyController? {

    var myWC: MyController?                
    for viewController in self.windowControllers {
        if ((viewController as? MyController) != nil) {
            myWC = viewController as? MyController
            break
        }
    }

    return myWC
}

// example of use
guard let myController = myXWindowController else {
    reportAssertionFailure("Failed to get MyXController from WindowController.")
    return
}  
0
 var top = window?.rootViewController
            while ((top?.presentedViewController) != nil) {
                top = top?.presentedViewController
            }
            
            if !(type(of: top!) === CallingVC.self) {
                top?.performSegue(withIdentifier: "CallingVC", sender: call)
            }
0
0

I chose to create my own enum to keep track of which view controller I was on:

enum currentViewController{
   case publicVC
   case homeVC
   case friendsVC
}

Then in each of your viewWillAppears change a global variable to equal the respective enum.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.