在 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/