Search code examples
swiftmacoscocoaappkitkeystroke

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


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.


Solution

  • 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