4

I'm building a macOS application that requires monitoring global keystrokes. So the global event listener would be:

NSEvent.addGlobalMonitorForEvents(matching: NSEvent.EventTypeMask.keyDown) { (event) in
          print(event.keyCode)
}

But this does nothing as mentioned in this thread. I did try the answer given in the thread by adding:

let options: NSDictionary = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String : true]
let accessEnabled = AXIsProcessTrustedWithOptions(options)
      

if !accessEnabled {
   print("Access Not Enabled")
} else {
   print("Access Granted")
}

This prompts the dialog box to request access but since it's an asynchronous process, giving access is still not moving the thread to a point where I can monitor keystrokes. Besides, this dialog box pops up on each launch of the app, how to curate this graceful requesting of accessibility without the hassle, as there's no proper documentation anywhere, as far as I searched.

Sabesh Bharathi
  • 171
  • 1
  • 9
  • did you enable the accessibility for your app in privacy settings? Once allowed it won't prompt again – RTXGamer Jan 22 '22 at 19:12
  • I did allow it in the settings. It is prompting again regardless, I go to check and see I've already given it permission. The prompt always pops up on building and running – Sabesh Bharathi Jan 23 '22 at 05:26
  • 1
    I'm on macOS Monterey 12.2 and it prompted the first time for the access and I enabled the accessibility. The second launch doesn't prompt access, keystrokes are getting captured. I'm running the source directly through Xcode though – RTXGamer Jan 23 '22 at 09:46
  • 1
    @RTXGamer Thanks for this information. Turns out, it's a macOS Bug (check answer) – Sabesh Bharathi Jan 23 '22 at 15:26

1 Answers1

2

I realized this is an Xcode bug instead. This is caused if the SwiftUI preview provider is run concurrently with the actual build, this causes some confusion with the accessibility permissions with macOS.

The application works as expected after the derived data directory is cleaned. You can do that with

rm -rf ~/Library/Developer/Xcode/DerivedData
Sabesh Bharathi
  • 171
  • 1
  • 9