4

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.

parker9
  • 141
  • 1
  • 4

1 Answers1

9

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)
parker9
  • 141
  • 1
  • 4