Search code examples
swiftmacosnsviewcontroller

How to check which NSViewController is active swift


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?


Solution

  • 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.