How to prompt for accessibility features in a macOS app (from the AppDelegate)?
Asked Answered
C

1

5

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.

Connect answered 22/1, 2022 at 16:33 Comment(4)
did you enable the accessibility for your app in privacy settings? Once allowed it won't prompt againPickaxe
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 runningConnect
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 thoughPickaxe
@Pickaxe Thanks for this information. Turns out, it's a macOS Bug (check answer)Connect
C
3

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
Connect answered 28/1, 2022 at 6:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.