OS X Application Connectivity Monitoring

I want to know from a Swift application when a user changes one application to another, usually generally.

For example: switching from Google Chrome to another application, such as Xcode, will trigger this event.

Is there a way to pick up application switching events, for example, through an event monitor?

+5
source share
2 answers

You can add an observer to NSWorkspace.sharedWorkspace().notificationCenter to view the NSWorkspaceDidActivateApplicationNotification key. You specify a selector on one of your methods and grab information from the userInfo dictionary.

A simple example in AppDelegate:

Swift 2.2

 func applicationDidFinishLaunching(notification: NSNotification) { NSWorkspace.sharedWorkspace().notificationCenter.addObserver(self, selector: #selector(activated), name: NSWorkspaceDidActivateApplicationNotification, object: nil) } func activated(notification: NSNotification) { if let info = notification.userInfo, app = info[NSWorkspaceApplicationKey], name = app.localizedName { print(name) } } 

Swift 3

 func applicationDidFinishLaunching(_ aNotification: Notification) { NSWorkspace.shared().notificationCenter.addObserver(self, selector: #selector(activated(_:)), name: NSNotification.Name.NSWorkspaceDidActivateApplication, object: nil) } func activated(_ notification: NSNotification) { if let info = notification.userInfo, let app = info[NSWorkspaceApplicationKey] as? NSRunningApplication, let name = app.localizedName { print(name) } } 
+7
source

In Swift 3, you need to use the let keyword for each optional binding. In addition, the running application extracted from the userInfo dictionary is of type any and must be added to the NSRunningApplication type.

So, the Swift 3 answer given by Eric Ayey, but needs minor modifications:

 func applicationDidFinishLaunching(_ aNotification: Notification) { NSWorkspace.shared().notificationCenter.addObserver(self, selector: #selector(activated), name: NSNotification.Name.NSWorkspaceDidActivateApplication, object: nil) } func activated(notification: NSNotification) { if let info = notification.userInfo, let app = info[NSWorkspaceApplicationKey] as? NSRunningApplication, let name = app.localizedName { print(name) } } 

(I would leave this post as a comment on the accepted answer, but not enough rep ...)

+5
source

All Articles