4

How I can use AXObserverAddNotification in Swift to detect an UI change?

There's a great answer here in Obj C.

How can my app detect a change to another app's window?

How to translate the answer to Swift?

The testing code below compiles and runs without an error, but callBack doesn't seem to get executed when I change main window.

    func observe(app:pid_t, element:AXUIElement) {
        var observer: AXObserver? = nil
        func callBack(observer: AXObserver?, element: AXUIElement?, notification: CFString, refcon: UnsafeMutableRawPointer?) {
            print("Fired! \(notification)")
        }
        if AXObserverCreate(app, callBack, &observer) == .success {
            print("AXObserverCreate success!")
            if AXObserverAddNotification(observer!, element, kAXMainWindowChangedNotification as CFString, UnsafeMutableRawPointer(Unmanaged.passRetained(self).toOpaque())) == .success {
                print("AXObserverAddNotification success!")
                CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer!), .defaultMode)
                print("Watching \(element.value(of:"AXTitle"))")
            }
        }
    }
jl303
  • 1,461
  • 15
  • 27

1 Answers1

1

@kyo-ago did a great job on encapsulating those C-like swift APIs in his project.

Henry
  • 481
  • 4
  • 17