I am simulating keystrokes in macOS, and sending them to the active application. I am doing it along the lines of https://stackoverflow.com/a/27487493/5600424 but in Swift 3. For example, to send an 'a':
let eventSource = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
let key: CGKeyCode = 0 // virtual key for 'a'
let eventDown = CGEvent(keyboardEventSource: eventSource, virtualKey: key, keyDown: true)
let eventUp = CGEvent(keyboardEventSource: eventSource, virtualKey: key, keyDown: false)
let location = CGEventTapLocation.cghidEventTap
eventDown.post(tap: location)
eventUp.post(tap: location)
This was working fine on OSX El Capitan (Swift 3, Xcode 8.0), but it stopped working after updating to macOs Sierra. The application itself still receives the keystroke when it's active, however when a different application is active the events seem lost. I have tried to figure out what is happening without success, and the documentation does not help. Any help would be appreciated, thanks!