Search code examples
objective-cxcodemacosapplescript

Passing variables to an AppleScript


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.


Solution

  • 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: