After spending a couple of hours on google, I eventually read a couple of github resources. It turns out that someone already understood this .
Basically, you need to create an NSApplicationDelegate
that allows your application to listen for system events.
The required minimum code ( swift2
) is shown below:
func acquirePrivileges() -> Bool { let accessEnabled = AXIsProcessTrustedWithOptions( [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true]) if accessEnabled != true { print("You need to enable the keylogger in the System Preferences") } return accessEnabled == true } class ApplicationDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(notification: NSNotification?) { acquirePrivileges() // keyboard listeners NSEvent.addGlobalMonitorForEventsMatchingMask( NSEventMask.KeyDownMask, handler: {(event: NSEvent) in print(event) }) } } // preparing main loop let application = NSApplication.sharedApplication() let applicationDelegate = MyObserver() application.delegate = applicationDelegate application.activateIgnoringOtherApps(true) application.run()
If you are only interested in exciting events without access (for example: NSWorkspaceDidActivateApplicationNotification
), you can leave with significantly fewer lines of code, since you only need NSRunLoop.mainRunLoop().run()
. I added this example only after I saw your while true
event while true
, which will never let you listen to any system events, since it blocks the main thread.
class MyObserver: NSObject { override init() { super.init()
source share