2

I would like to pass a variable to applescript. For example, I type some words in textfield of a Cocoa-App (not cocoa-applescript app).Then, it will be a variable in Applescript for future use. I use Applescript to tell some software to run some files.

I've tried How Can I Pass a String From Applescript to Objective C the method here. It could add the first lines in applescript using initialwithSource. I have to write a long sentence. Also if I've already have the applescript, I have to either combine them together. Or I have to write all the script in Cocoa like below. It's meaningless and sometimes it doesn't work well.

NSString *SlideURL = [NSString stringWithFormat:@"set mypath to \"%@\" \n tell application \"Keynote\" \n open mypath \n tell slideshow %@ \n start slideshow\n end tell \n end tell\n",temp,temp];

// here is meaningless right
// temp is the variable I want to pass to applescript 

NSDictionary *errorInfo = nil;
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:SlideURL];
[script executeAndReturnError:&errorInfo];
[script release];

Do anyone of you know a better way ?

Thanks

Community
  • 1
  • 1
user2152814
  • 257
  • 1
  • 7
  • 17

1 Answers1

2

String mashing is evil. Just use AppleScriptObjC; there's no magic or complexity to it.

Assuming your application is built using the Cocoa Application template, you will need to 1. include the AppleScriptObjC framework in your project and 2. modify its main.m to match the ASOC template's main.m, which contains two extra lines:

#import <Cocoa/Cocoa.h>

#import <AppleScriptObjC/AppleScriptObjC.h>

int main(int argc, char *argv[])
{
    [[NSBundle mainBundle] loadAppleScriptObjectiveCScripts];
    return NSApplicationMain(argc, (const char **)argv);
}

Once you've done that, you can add ASOC-style script object files to your project and they'll look just like native classes to the rest of your ObjC program, e.g.:

-- FooTest.applescript

script FOOTest
    property parent : class "NSObject"

    on doSomething_(sender)
        display dialog "Hello World"
    end 

end script

See this answer for useful links.

Community
  • 1
  • 1
foo
  • 3,171
  • 17
  • 18
  • This answer was very helpful, though it seems to be missing a step. I couldn't get my embedded .applescript file to execute any of its class methods initially. I found the solution to be going to Target → Build Phases → Compile Sources → add my .applescript file to the list there. Also, if you have enabled Hardened Runtime in your project, you may need to enable sending of Apple Events (it's a checkbox to turn on/off). – William Gustafson Feb 01 '21 at 15:48