swift - 尝试在 Swift mac os App 中集成苹果脚本以获取 macOS 上应用程序的 gui 元素
问题描述
尝试在 Swift mac os App 中集成苹果脚本并得到以下错误 NSAppleScriptErrorBriefMessage = "Not authorized to send Apple events to System Events.";
以下是脚本
activate application "Calendar"
delay 0.1
tell application "System Events"
tell front window of application process "Calendar"
set uiElems to entire contents
end tell
end tell
"""
以下是整个代码
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Create the window and set the content view.
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
window.center()
window.setFrameAutosaveName("Main Window")
window.contentView = NSHostingView(rootView: contentView)
window.makeKeyAndOrderFront(nil)
let myAppleScript = """
activate application "Calendar"
delay 0.1
tell application "System Events"
tell front window of application process "Calendar"
set uiElems to entire contents
end tell
end tell
"""
var error: NSDictionary?
if let scriptObject = NSAppleScript(source: myAppleScript) {
if let output: NSAppleEventDescriptor = scriptObject.executeAndReturnError(
&error) {
print(output)
} else if (error != nil) {
print("error: \(error)")
}
}
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
我试过 1)在可访问性中添加 Xcode、日历 2)向 plist 添加条目
有没有人遇到过这个问题
解决方案
为了让应用程序通过 Apple Events 与其他应用程序通信,您需要在 Xcode 项目中配置一些东西:
- Apple Events 的一般权利
- 您要编写脚本的应用程序的特定权利,如果它是较旧的应用程序,则使用“临时例外”或支持它的较新应用程序的特定访问权限
- 一个 Info.plist 条目,导致系统提示您的应用程序的脚本权限
这是 Apple 事件的权利文件条目以及应用程序的临时异常(通过其捆绑 ID)的示例:
<key>com.apple.security.automation.apple-events</key>
<true/>
<key>com.apple.security.temporary-exception.apple-events</key>
<string>com.apple.QuickTimePlayerX</string>
这是所需的 Info.plist 条目的示例:
<key>NSAppleEventsUsageDescription</key>
<string>Please give ScreenRecordingDetector access to Quicktime Player via Apple Script.</string>
一些相关文档:
推荐阅读
- javascript - 使用 jsPDF 从 iframe 创建 PDF
- php - 比较两个数组并查找特定值中的所有重复项(php)
- c - 为什么我的求和程序表现得很奇怪?
- vhdl - 实例化组件的生成语句中的编译错误
- botframework - 通过 Bot Nodejs 从 Teams 下载附件
- traefik - traefik 仪表板可以设置为通过 HTTPS 侦听吗?
- php - PHP 中的 SQL 数据库创建错误(多个 SQL 连接)
- laravel-5 - 如何更改方法类 orm Laravel 中的密钥 ID?
- c - 如何优化 MAC 的搜索
- prolog - 结果未保存在序言变量上