objective-c - 将变量传递给 AppleScript

标签 objective-c xcode macos applescript

在 Xcode 中运行我的 AppleScript 的代码如下:

NSString *path = [[NSBundle mainBundle] pathForResource:@"Script" ofType:@"scpt"];

NSAppleScript *script = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];

[script executeAndReturnError:nil];

在执行它之前,我想知道是否可以设置一些变量供它使用。换句话说,我想将变量从我的应用程序传递到 AppleScript。

最佳答案

我找到的最好的例子是来自 Quinn “The Eskimo!” 的这段代码。在 Apple 开发者论坛上:

https://forums.developer.apple.com/thread/98830

AppleScript 文件:

on displayMessage(message)  
    tell application "Finder"  
        activate  
        display dialog message buttons {"OK"} default button "OK"  
    end tell  
end displayMessage 

从 Swift 调用 AppleScript 方法,传递参数:

import Carbon

// ...

let parameters = NSAppleEventDescriptor.list()
parameters.insert(NSAppleEventDescriptor(string: "Hello Cruel World!"), at: 0)

let event = NSAppleEventDescriptor(
    eventClass: AEEventClass(kASAppleScriptSuite),
    eventID: AEEventID(kASSubroutineEvent),
    targetDescriptor: nil,
    returnID: AEReturnID(kAutoGenerateReturnID),
    transactionID: AETransactionID(kAnyTransactionID)
)
event.setDescriptor(NSAppleEventDescriptor(string: "displayMessage"), forKeyword: AEKeyword(keyASSubroutineName))
event.setDescriptor(parameters, forKeyword: AEKeyword(keyDirectObject))

let appleScript = try! NSUserAppleScriptTask(url: yourAppleScriptFileURL)
appleScript.execute(withAppleEvent: event) { (appleEvent, error) in
    if let error = error {
        print(error)
    }
}

关于objective-c - 将变量传递给 AppleScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8917050/

相关文章:

xcodebuild 标志覆盖 pods 项目目标的代码签名

xcode - 将数组与不同的数组类型进行比较

java - "Your java version is out of date"带有最新的java

xcode - 无法将 nsnumber 类型的值分配给值类型字符串

iphone - XCode 4 - 在调试期间观察自定义变量的值

ios - 我们可以为 iphone 和 mac 应用程序使用相同的 Crashlytics 应用程序吗

iOS CoreBluetooth 更新值 : and didUpdateValueForCharacteristic:

objective-c - keyDown 有效,但我听到哔哔声

objective-c - 如何获取项目文件夹中以特定字符串开头的所有图像

iphone - IOS注销时如何释放app保留的对象或内存