Swift-获取另一个应用程序中当前打开的文档的文件路径
我正在尝试使用swift代码从另一个应用程序获取打开文档的文件路径。我知道如何在AppleScript中执行此操作,如下所示:Swift-获取另一个应用程序中当前打开的文档的文件路径,swift,xcode,macos,accessibility,axuielement,Swift,Xcode,Macos,Accessibility,Axuielement,我正在尝试使用swift代码从另一个应用程序获取打开文档的文件路径。我知道如何在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 en
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中实现它。我知道一种选择是从我的程序中运行这个脚本,但我希望找到另一种方法,可能不使用可访问性
在我的应用程序中,我可以通过执行以下操作将应用程序作为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)
}
我只是不知道一旦我做了AXUIElement该怎么办。任何帮助都将不胜感激。感谢@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)
}
}
这将像AppleScript一样获取AXDocument。仍然可以使用其他方法来实现这一点,这些方法可能更好,也可能不使用可访问性 谢谢分享。这正是我需要的