I'm trying to make use of Accesibility API in Swift, to register for notifications of window properties of the current frontmost app. However I couldn't find any examples/detailed info about AXObserverCreate function in swift. There is one really good answer for objective-C, and also for swift 2.2 here, but I believe I'm facing a syntax-ish error here since I'm trying to convert it to Swift 4 -which I am quite newbie at-.
Here is the code I'm trying:
let currentApp:AXUIElement = AXUIElementCreateApplication(app.processIdentifier)
var obs: AXObserver? = nil
// Observer created with closure, it doesn't work otherwise. 'app' is the current frontmost app as NSRunningApplication
let axErr:AXError = AXObserverCreate(app.processIdentifier, { (observer: AXObserver, element: AXUIElement, notificationName: CFString, refcon: UnsafeMutableRawPointer?) -> Void in
print("CALLBACK SUCCESS") // Never reads this callback line??
}, &obs)
if axErr != AXError.success {
print("error") }
// Here the notification added, even though I tried with many other notification types, I couldn't make it work.
let notifErr:AXError = AXObserverAddNotification(obs!, currentApp, kAXMainWindowChangedNotification as CFString, nil)
if notifErr != AXError.success {
print("error")}
//Observer is also added to CFRunLoop, not sure if it makes any difference
CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(obs!), CFRunLoopMode.defaultMode)
I'm guessing it could be a problem about unwrapped and optional values of the observer, because I think I didn't completely understand how '?' and '!' work so far.
Any help/feedback would be greatly appreciated, thanks and happy coding!