swift 未被授权将Apple事件发送到Finder,(错误-1743)

ui7jx7zq  于 2023-01-29  发布在  Swift
关注(0)|答案(1)|浏览(767)

我不可能从XCode运行Apple Script,下面是我尝试让它工作的方法:

let appleScript = NSAppleScript(source: script)
                var error: NSDictionary?
                if let outputString = appleScript?.executeAndReturnError(&error).stringValue {
                    print(outputString)
                } else if (error != nil) {
                    print("error: \(error!)")
                }`

我在输出中得到这个错误:

error : {
    NSAppleScriptErrorAppName = Finder;
    NSAppleScriptErrorBriefMessage = "Not authorized to send Apple events to Finder.";
    NSAppleScriptErrorMessage = "Not authorized to send Apple events to Finder.";
    NSAppleScriptErrorNumber = "-1743"
    NSAppleScriptErrorRange = "NSRange: {63,1O}"

我已经做了here所描述的一切,并检查了我的权利文件上的每一个权限。“苹果事件”设置为“是”,但这仍然不起作用。
我真的被困在这里了。有什么建议吗?我在 Monterey 。

6yjfywim

6yjfywim1#

我找到了一个解决办法:将applescript.scpt文件放入我的应用程序的资源中,并使用以下命令调用它:

AppKit.NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDown) { event in
        let task = Process()
        if let path = Bundle.main.path(forResource: "getpathscript.scpt", ofType: nil) {
            task.launchPath = "/usr/bin/osascript"
            task.arguments = ["\(path)"]
            let pipe = Pipe()
            task.standardOutput = pipe
            task.launch()
            let data = pipe.fileHandleForReading.readDataToEndOfFile()
            filepath = (String(data: data, encoding: .utf8)?.trimmingCharacters(in: .newlines))!
        }
    }

希望这个有用。

相关问题