gpt4 book ai didi

swift - 我的 cocoa mac 应用程序中使用的 AppleScript 在 osx 10.14 中停止工作

转载 作者:搜寻专家 更新时间:2023-11-01 05:54:38 24 4
gpt4 key购买 nike

我使用 AppleScript 从第三方应用程序中获取选定的文本。这在 osx 10.13 中工作正常但在 osx 10.14 中停止工作。

通过搜索,得到一个在 info.plist 中添加“NSAppleEventsUsageDescription”的建议,但这对我也不起作用。

let latestApp = "Safari"

//Write script to activate the app and get the selected text to our app
let script = """
tell application \"\(latestApp)\"
activate
end tell
tell application \"System Events\"
tell process \"\(latestApp)\"
keystroke \"c\" using {command down}
delay 0.1
set myData to (the clipboard) as text
return myData
end tell
end tell
"""
let scriptObject = NSAppleScript.init(source: script)
let errorDict: AutoreleasingUnsafeMutablePointer<NSDictionary?>? = nil
var returnDescription:NSAppleEventDescriptor? = nil
returnDescription = scriptObject?.executeAndReturnError(errorDict)
if( returnDescription != nil ){
if( kAENullEvent != returnDescription?.descriptorType ){ //successful execution
if( cAEList == returnDescription?.descriptorType ){
print("return value")
}else{
print("Returned string : \(String(describing: returnDescription?.stringValue))")
let selectedStr = returnDescription?.stringValue!
if( (selectedStr?.count)! > 0 ){
print("selectedStr is :\(String(describing: selectedStr))")
}
}
}

}else{
print("Error is : \(String(describing: errorDict))")

}

它在 os 10.12 和 10.13 以及 ScriptEditor 中也能完美运行。

enter image description here

最佳答案

因为您要告诉“Safari”激活,所以没有必要使用“系统事件”来告诉进程“Safari”...。简单地使用 "System Events"keystroke "c"using {command down} 完成同样的事情。这不是什么大不了的事,但在各处消除了不必要的代码行,使浏览代码更容易、更清晰。此外,如果不使用 {command down} 命令在 keystroke "c"之前添加额外的 delay 0.3,我的系统有 50% 的时间会返回一个空的剪贴板。

此 AppleScript 代码适用于使用最新版本的 macOS Mojave 的我。

tell application "Safari" to activate
delay 0.2 -- Adjust As Needed
tell application "System Events" to keystroke "c" using {command down}
set myData to (the clipboard) as text

由于clipboard 命令是由Standard Additions 而不是System Events 处理的(正如@user3439894 在他的评论中提到的),删除set myData to (the clipboard) as text from the System Events tell block ,允许我成功删除 delay 0.1 命令。

或选项 2

实际上,转念一想,如果您只想在 Safari 中使用它,那么下面一行 AppleScript 代码就可以满足您的需要。

您必须在 Safari 的“开发”菜单中启用允许来自 Apple 事件的 JavaScript 选项才能使用执行 JavaScript

tell application "Safari" to set myData to (do JavaScript "''+document.getSelection()" in document 1)

我只解决了 AppleScript 部分,因为@matt 在他的帖子中彻底涵盖了所有其他问题。

关于swift - 我的 cocoa mac 应用程序中使用的 AppleScript 在 osx 10.14 中停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55917877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com