【问题标题】:How to use AXObserver in Swift如何在 Swift 中使用 AXObserver
【发布时间】:2021-05-15 09:23:10
【问题描述】:

我试图在另一个应用程序使用 Accessibility API 和 AXObserver 创建窗口时收到通知。这是我的代码:

    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) 

我错过了什么吗?代码编译并运行,但我的回调没有被执行。 有通知进来时回调会执行吗?

【问题讨论】:

标签: swift macos cocoa


【解决方案1】:

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

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

您的var observer: AXObserver? 已被解除分配,因此您将永远不会接到电话。您需要在某处保留对您的 AXObserver 的引用。

祝你好运。 AX API 很痛苦。

【讨论】:

    猜你喜欢
    • 2013-02-24
    • 2016-05-26
    • 2015-09-21
    • 2021-04-05
    • 2014-09-18
    • 2017-08-05
    • 2014-10-26
    • 2018-12-12
    • 2014-10-27
    相关资源
    最近更新 更多