swift 如何使用AXObserverAddNotification?

o7jaxewo  于 2022-12-22  发布在  Swift
关注(0)|答案(1)|浏览(104)

我想在窗口焦点更改时触发函数
如何基于kAXFocusedWindowChangedNotification添加观察者
我试着这样使用:

override func viewDidLoad() {
  super.viewDidLoad()

  var observer: AXObserver? = nil
  let pid_app: pid_t = NSWorkspace.shared.runningApplications.first(where: {$0.localizedName == "Safari"})!.processIdentifier as pid_t
  let app_ref = AXUIElementCreateApplication(pid_app)
  func callBack(observer: AXObserver?, element: AXUIElement?, notification: CFString, refcon: UnsafeMutableRawPointer?) {print("Fired!")}
      if AXObserverCreate(pid_app, callBack, &observer) == .success {
         print("AXObserverCreate success!")
      if AXObserverAddNotification(observer!, app_ref, kAXFocusedWindowChangedNotification as CFString, UnsafeMutableRawPointer(Unmanaged.passRetained(self).toOpaque())) == .success {
         print("AXObserverAddNotification success!")
         CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer!), .defaultMode)
         print("Watching")
         }
      }
}

那么,为什么当我改变safari的窗口焦点时没有触发func回调呢?

lf5gs5x2

lf5gs5x21#

正如@Willeke已经指出的,您需要保留对observer的引用(可能您希望将其作为属性)。
对于其他感兴趣的人,也可以看看https://stackoverflow.com/a/33262376/1531256的答案,它解释了如何将self传递给回调C函数。

相关问题