Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when user changes Spaces on macOS?

I'm trying to get an macOS application to detect when the user switches Spaces.

Mostly following this suggestion (Detecting when a space changes in Spaces in Mac OS X) though updated to

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {

        NotificationCenter.default.addObserver(self, selector: #selector(self.spaceChange), name: NSWorkspace.activeSpaceDidChangeNotification, object: nil)
    }

    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        return true
    }

    @objc func spaceChange() {
        print("space did change")
    }

}

which appears to be fine, at least it compiles w/o warning/error.

I expect "space did change" to be printed to the log when the app is running when I do switch Spaces. However, it never does print to the log.

like image 363
parker9 Avatar asked Nov 16 '25 18:11

parker9


1 Answers

Yes, the problem here is that i used the wrong NotificationCenter, we need:

NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(self.spaceChange), name: NSWorkspace.activeSpaceDidChangeNotification, object: nil)
like image 134
parker9 Avatar answered Nov 18 '25 10:11

parker9



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!