Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(OS X) How to be notified when user switches mac desktop space

Tags:

I'm creating a Mac menu bar app that I'd like to be notified when the user switches the visible desktop space (including external monitors). This is a menu bar only app (i.e no actual window).

I've seen a few similar questions, but none of the answers seemed to work for me. Most answers I've seen involve observing NSWorkspaceActiveSpaceDidChangeNotification on the NSWorkspace's notification center.

I've tried observing this in my AppDelegate in applicationDidFinishLaunching I have the following code:

NSWorkspace.sharedWorkspace().notificationCenter.addObserver(self, selector: Selector(spaceChanged()), name: NSWorkspaceActiveSpaceDidChangeNotification, object: nil)

In my spaceChanged() function I'm just printing something to console for debugging purposes. This function only ever gets called on app launch. Whenever I change the desktop space though I never get notified.

Is there something I'm missing? Any help is appreciated.

like image 258
chetem Avatar asked May 06 '16 07:05

chetem


2 Answers

Rather than Selector(spaceChanged()) you should use #selector(spaceChanged). With Selector(spaceChanged()), you're actually calling this function immediately, and using the result (which is probably just an empty tuple ()) to create a null selector. The latter syntax actually creates the proper selector referencing your spaceChanged function.

like image 176
jtbandes Avatar answered Sep 28 '22 03:09

jtbandes


An update for Swift:

    NSWorkspace.shared.notificationCenter.addObserver(
        self,
        selector: #selector(spaceChanged),
        name: NSWorkspace.activeSpaceDidChangeNotification,
        object: nil
    )
like image 44
appsmatics Avatar answered Sep 28 '22 01:09

appsmatics