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?
-
Hey Niktin, Are you loading some kind of container controller that will hold these view controllers, like a TabBar controller, or a Navigation controller? – Ryan Jan 15 '15 at 16:26
-
No, there are just some viewcontrollers, connected with segues – Jan 15 '15 at 16:35
-
window.view.rootViewController ? (this may be iOS only) – Jan 15 '15 at 16:39
-
What actually do you mean by "is active"? Whether it has focus? – qwerty_so Jan 15 '15 at 16:44
-
@ThomasKilian yes, when the user works with it – Jan 15 '15 at 16:55
-
@Okapi, this doesn't work – Jan 15 '15 at 16:56
-
@NiktinRoman what does not work? Is there an error message? – Sebastian Jan 15 '15 at 18:25
-
@SebastianDressler yes, (use of unresolved identifier "window", written in AppDelegate) – Jan 15 '15 at 18:56
3 Answers
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.

- 266
- 1
- 4
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.

- 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
-
1You can get the active window by calling [UIApplication sharedApplication].keyWindow. – Ryan Jan 15 '15 at 18:54
-
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()
}
}

- 97
- 3