Skip to content

Instantly share code, notes, and snippets.

@kaydell
Last active December 20, 2015 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaydell/6189741 to your computer and use it in GitHub Desktop.
Save kaydell/6189741 to your computer and use it in GitHub Desktop.
Running AppleScripts, from Cocoa by calling the command-line tool, osascript
// This method executes an AppleScript given the source-code, using the command-line tool called osascript
// Note that this is a demo and doesn't do any error-checking yet such as for AppleScript syntax errors
// and AppleScript runtime errors.
+ (void)execute:(NSString *)source
{
@try {
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/osascript"];
NSString *arguments = [NSString stringWithFormat:@"-e %@", source];
[task setArguments:[NSArray arrayWithObjects:arguments, nil]];
[task launch];
[task waitUntilExit];
NSLog(@"osascript succeeded");
} @catch (NSException *e) {
NSLog(@"osascript failed, reason: %@", [e reason]);
}
}
// This method calls the execute method to execute a simple AppleScript
- (IBAction)test01:(id)sender
{
NSString *source = @"say \"Hello World\"\n";
[AppDelegate execute:source];
}
// This method calls the execute method to execute an AppleScript that is a little more complicated
// and does user-interaction
- (IBAction)test02:(id)sender
{
NSString *source = @"tell application \"Finder\"\n"
@" activate\n"
@" delay 1\n"
@" try\n"
@" «event GKKJload»\n"
@" on error msg number num\n"
@" display dialog \"another try\" buttons{\"i see\"} default button 1 with icon caution with title \"aaa\"\n"
@" end try\n"
@"end tell";
[AppDelegate execute:source];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment