简体   繁体   English

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

[英]Swift - Get file path of currently opened document in another application

I am attempting to get the file path of an open document from another application using swift code.我正在尝试使用 swift 代码从另一个应用程序获取打开文档的文件路径。 I know how to do it in AppleScript, which is like this:我知道如何在 AppleScript 中做到这一点,就像这样:

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

This AppleScript does what I want, but I was hoping to do it natively in Swift.这个 AppleScript 做了我想要的,但我希望能在 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.我知道一个选择是从我的程序中运行这个脚本,但我希望找到另一种方法,可能不使用辅助功能。

In my app I can get the application as a AXUIElement by doing the following:在我的应用程序中,我可以通过执行以下操作将应用程序作为 AXUIElement 获取:

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)
}

I'm just not sure what to do with the AXUIElement once I make it.我只是不确定一旦我制作了 AXUIElement 该怎么办。 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:感谢@JamesWaldrop 的另一篇文章的帮助,我能够自己回答这个问题,并想在这里发帖供任何寻找类似内容的人使用:

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)
    }
}

This gets the AXDocument just like the AppleScript does.这就像 AppleScript 一样获取 AXDocument。 Would still be open to other methods of doing this that may be better or not using Accessibility.仍然会接受其他可能更好或不使用辅助功能的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM