3

I tried to get notified when another Application creates a window using the Accessibility API and AXObserver. Here's my code:

    let pid = NSWorkspace.shared.frontmostApplication!.processIdentifier
    var observer: AXObserver?
    if AXObserverCreate(pid, { (observer, element, notification, userData) in
        // Does this get executed when a notification comes in?
        print(notification)
    }, &observer) == .success {
        // This does get printed!
        print("Successfully created Observer!")
    }
    
    if AXObserverAddNotification(observer!, element, notification, nil) == .success {
        // This also gets printed!
        print("Successfully added Notification!")
    }
    
    CFRunLoopAddSource(RunLoop.current.getCFRunLoop(), AXObserverGetRunLoopSource(observer!), CFRunLoopMode.defaultMode) 

Am I missing something? The code compiles and runs, but my calback doesn't get executed. Does the callback get executed when a notification comes in?

techrisdev
  • 606
  • 4
  • 10
  • See [How to Use AXObserverAddNotification in Swift?](https://stackoverflow.com/questions/48825816/how-to-use-axobserveraddnotification-in-swift) – Willeke Feb 11 '21 at 16:06
  • Is `observer` deallocated when it goes out of scope? – Willeke Feb 11 '21 at 16:14

1 Answers1

0

see: https://developer.apple.com/documentation/applicationservices/1459139-axobservergetrunloopsource

Note that releasing the AXObserverRef automatically removes the run loop source from the run loop

your var observer: AXObserver? is deallocated so you'll never get the call. you need to keep a reference to your AXObserver somewhere.

good luck. the AX API is a pain.

godbout
  • 1,765
  • 1
  • 12
  • 11