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

Shr*_*ngh 0 macos xcode applescript swift

尝试在 Swift mac os 应用程序中集成 Apple 脚本并收到以下错误 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
"""
Run Code Online (Sandbox Code Playgroud)

以下是整个代码

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
    }


}
Run Code Online (Sandbox Code Playgroud)

我尝试过 1)在辅助功能中添加 Xcode、日历 2)向 plist 添加条目

有没有人遇到过这个问题

Cor*_*ell 6

为了让应用程序通过 Apple Events 与其他应用程序进行通信,您需要在 Xcode 项目中配置一些内容:

  1. Apple 活动的一般权利
  2. 您想要编写脚本的应用程序的特定权利,如果它是较旧的应用程序,则使用“临时异常”,或者为支持它的较新应用程序使用特定的访问权利
  3. 一个 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>
Run Code Online (Sandbox Code Playgroud)

以下是所需的 Info.plist 条目的示例:

<key>NSAppleEventsUsageDescription</key>
<string>Please give ScreenRecordingDetector access to Quicktime Player via Apple Script.</string>
Run Code Online (Sandbox Code Playgroud)

一些相关文档:

QA1888 OS X 中的沙箱和自动化

应用程序沙箱临时例外权利