首页 > 解决方案 > 尝试在 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 添加条目

有没有人遇到过这个问题

标签: swiftxcodemacosapplescript

解决方案


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

  1. Apple Events 的一般权利
  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>

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

<key>NSAppleEventsUsageDescription</key>
<string>Please give ScreenRecordingDetector access to Quicktime Player via Apple Script.</string>

一些相关文档:

QA1888 OS X 中的沙盒和自动化

应用沙盒临时例外权利


推荐阅读