在Xcode中运行我的AppleScript的代码如下:
NSString *path = [[NSBundle mainBundle] pathForResource:@"Script" ofType:@"scpt"];
NSAppleScript *script = [[NSAppleScript alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
[script executeAndReturnError:nil];
在执行它之前,我想知道是否可以设置一些变量供它使用。换句话说,我希望将变量从我的应用程序传递给AppleScript。
发布于 2012-01-19 04:43:14
你可以使用下面的方法:
- (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:
替换它们
发布于 2018-09-28 04:31:35
我找到的最好的例子是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)
}
}
发布于 2022-01-08 14:38:24
具有返回值处理的版本。(基于Quinn的代码)
import Carbon
// ...
let script = """
on displayMessage(message)
display dialog message
return "hello…"
end displayMessage
"""
let handler = NSAppleEventDescriptor(string: "displayMessage")
let message = NSAppleEventDescriptor(string: "Hello AppleScript!")
let parameters = NSAppleEventDescriptor.list()
parameters.insert(message, at: 0)
let event = NSAppleEventDescriptor(
eventClass: AEEventClass(kASAppleScriptSuite),
eventID: AEEventID(kASSubroutineEvent),
targetDescriptor: nil,
returnID: AEReturnID(kAutoGenerateReturnID),
transactionID: AETransactionID(kAnyTransactionID)
)
event.setDescriptor(handler, forKeyword: AEKeyword(keyASSubroutineName))
event.setDescriptor(parameters, forKeyword: AEKeyword(keyDirectObject))
var error: NSDictionary?
if let appleScript = NSAppleScript(source: script) {
if let outputString = appleScript.executeAppleEvent(event, error: &error).stringValue {
print("output: ", outputString)
} else if (error != nil) {
print("error: ", error!)
}
}
https://stackoverflow.com/questions/8917050
复制相似问题