6

I have an app with multiple ViewControllers and I need to check which ViewController is active at the moment in AppDelegate. For example, I'll create a timer that runs function that checks if the particular ViewController is active and if it is, do some stuff. Is there any way to do that?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304

3 Answers3

4
NSApplication.sharedApplication().keyWindow

Will return the current window that has keyboard access. From there you can introspect on the NSWindow object to determine which it is.

Also if you have a need for it to programmatically active windows.

NSApplication.sharedApplication().windows

Will return an array of NSWindows in your application currently open.

window.makeKeyAndOrderFront(sender)

Will bring the window in focus, even from being minimized and make it the key window for keyboard control.

window.makeKeyWindow()

Will just bring the window in focus and make it the key window. It won't bring it out of minimization.

Thomas Alvarez
  • 266
  • 1
  • 4
2

You can get this information by accessing the root view controller in AppDelegate or anywhere else:

let activeController = window.rootViewController

However, since you want to use a timer to execute some code in that view controller, it might be more preferable to send a NSNotification. Since the "active" view controller should be aware, that it is active, you can specifically connect and disconnect the notification listeners.

Sebastian
  • 8,046
  • 2
  • 34
  • 58
  • Thanks much, but the code you've written is not working (use of unresolved identifier "window", written in AppDelegate), but the idea with NSNotification seems good –  Jan 15 '15 at 18:51
  • 1
    You can get the active window by calling [UIApplication sharedApplication].keyWindow. – Ryan Jan 15 '15 at 18:54
  • for macos it is `window.contentViewController` – ychz Jan 05 '20 at 17:33
0

I use this pattern in my AppDelegate to see which view controller has the document I'm currently working on:

 var vc: ViewController? = nil

 func iHaveFocus() -> Bool {
        let win = NSApplication.shared.keyWindow
        if (win != nil) {
            vc = win!.contentViewController as? ViewController
            if (vc != nil) {
                return true
            }
        } else {
            vc = nil
        }
        return false
    }

// Then to see which document gets something like a paste...

 @IBAction func pasteStuff(_ sender: Any) {
    if (iHaveFocus()) {
        vc!.pasteStuff()
    }
}