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

ぃ、小莉子 提交于 2019-12-01 23:10:50

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!