Swift-在另一个应用程序中获取当前打开的文档的文件路径

问题描述:

我正在尝试使用快速代码从另一个应用程序获取打开文档的文件路径.我知道如何在AppleScript中做到这一点,就像这样:

I am attempting to get the file path of an open document from another application using swift code. I know how to do it in AppleScript, which is like this:

tell application "System Events"

if exists (process "Pro Tools") then

    tell process "Pro Tools"

        set thefile to value of attribute "AXDocument" of window 1

    end tell

end if

end tell

这个AppleScript可以实现我想要的功能,但是我希望可以在Swift中原生地执行它.我知道一种选择是从程序中运行此脚本,但是我希望找到另一种执行此方法的方法,可能不使用辅助功能.

This AppleScript does what I want, but I was hoping to do it natively in Swift. I know that one option is to run this script from my program, but I was hoping to find another way of doing it, potentially without using Accessibility.

在我的应用程序中,可以通过执行以下操作将应用程序作为AXUIElement获取:

In my app I can get the application as a AXUIElement by doing the following:

let proToolsBundleIdentifier = "com.avid.ProTools"
let proToolsApp : NSRunningApplication? = NSRunningApplication
        .runningApplications(withBundleIdentifier: proToolsBundleIdentifier).last as NSRunningApplication?


if let app = proToolsApp {
    app.activate(options: .activateAllWindows)
}


if let pid = proToolsApp?.processIdentifier {   
    let app = AXUIElementCreateApplication(pid)
}

一旦确定,我不确定该如何处理AXUIElement.任何帮助将不胜感激.

I'm just not sure what to do with the AXUIElement once I make it. Any help would be greatly appreciated.

感谢

Thanks to the help of another post from @JamesWaldrop, I was able to answer this myself and wanted to post here for anyone looking for something similar:

let proToolsBundleIdentifier = "com.avid.ProTools"
let proToolsApp : NSRunningApplication? = NSRunningApplication
        .runningApplications(withBundleIdentifier: proToolsBundleIdentifier).last as NSRunningApplication?


if let pid = proToolsApp?.processIdentifier {

    var result = [AXUIElement]()
    var windowList: AnyObject? = nil // [AXUIElement]

    let appRef = AXUIElementCreateApplication(pid)
    if AXUIElementCopyAttributeValue(appRef, "AXWindows" as CFString, &windowList) == .success {
            result = windowList as! [AXUIElement]
    }

    var docRef: AnyObject? = nil
    if AXUIElementCopyAttributeValue(result.first!, "AXDocument" as CFString, &docRef) == .success {
        let result = docRef as! AXUIElement
        print("Found Document: \(result)")
        let filePath = result as! String
        print(filePath)
    }
}

这与AppleScript一样获得AXDocument.仍然可以接受其他可能更好或不使用辅助功能的方法.

This gets the AXDocument just like the AppleScript does. Would still be open to other methods of doing this that may be better or not using Accessibility.