Passing variables to an AppleScript

走远了吗. 提交于 2019-12-17 17:01:02

问题


The code to run my AppleScript in Xcode is the following:

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

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

[script executeAndReturnError:nil];

Before executing it, I was wondering if it was possible to set some variables up for it to use. In other words, I want to pass variables from my app to an AppleScript.


回答1:


You could use the method:

- (id)initWithSource:(NSString *)source

and use stringWithFormat to build your applescript source and setting the arguments.

NSString* scriptTemplate = ...;
NSString* actualScript = [NSString stringWithFormat:scriptTemplate, arg1, arg2, ... argN];
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:actualScript];

You could also devise a more advanced replacement mechanism, where you tag somehow your parameters in "Script.scpt" and then replace them using stringByReplacingOccurrencesOfString:withString:




回答2:


The best example I've found is this code from Quinn "The Eskimo!" on the Apple Developer Forums:

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

AppleScript file:

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

Call the AppleScript method from Swift, passing parameters:

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)
    }
}


来源:https://stackoverflow.com/questions/8917050/passing-variables-to-an-applescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!