在Xcode中运行AppleScript的代码如下:
NSString *path = [[NSBundle mainBundle] pathForResource:@"Script" ofType:@"scpt"];
NSAppleScript *script = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
[script executeAndReturnError:nil];
在执行之前,我想知道是否可以设置一些变量供它使用。换句话说,我想将变量从我的应用程序传递给AppleScript。
答案 0 :(得分:4)
您可以使用以下方法:
- (id)initWithSource:(NSString *)source
并使用stringWithFormat
构建您的applescript源并设置参数。
NSString* scriptTemplate = ...;
NSString* actualScript = [NSString stringWithFormat:scriptTemplate, arg1, arg2, ... argN];
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:actualScript];
您还可以设计一种更高级的替换机制,您可以在“Script.scpt”中以某种方式标记您的参数,然后使用stringByReplacingOccurrencesOfString:withString:
替换它们
答案 1 :(得分:2)
我发现的最好的例子是奎因(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方法,并传递参数:
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)
}
}