尝试在 Swift mac OS 应用程序中集成苹果脚本,以获取 macOS 上应用程序的 gui 元素



尝试在 Swift mac OS 应用程序中集成苹果脚本并收到以下错误NSAppleScriptErrorBriefMessage ="无权将 Apple 事件发送到系统事件";

以下是脚本

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中添加了条目

有没有人遇到过这个问题

为了让 App 通过Apple Events 与其他 App 通信,您需要在 Xcode 项目中配置一些内容:

  1. 苹果活动的一般权利
  2. 要编写脚本的应用程序的特定授权,如果它是较旧的应用,则使用"临时例外",或者支持它的较新应用的特定访问权利
  3. 一个 Info.plist 条目,它使系统提示输入应用的脚本权限

下面是 Apple Events 的授权文件条目以及应用程序的临时例外(按其捆绑 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>

一些相关文档:

QA1888 OS X 中的沙盒和自动化

应用沙盒临时例外权利

最新更新