Run AppleScript file in Mac application?

I am looking for a way to execute an Applescript file from a Mac App. I made previous Mac apps that use NSAppleScript *script = [[NSAppleScript alloc] initWithSource: @"MY_CODE"]]; but my applescript is quite long and I would just like to be able to link to this file as part of my project and the pipe to its contents (or just execute the file from my application).

Thanks!

+6
source share
2 answers

To run user-supplied AppleScripts outside the sandbox (10.8+), use NSUserAppleScriptTask

To run .scpt files embedded in your application suite or user scripts in 10.7 or earlier, use NSAppleScript .

NSUserAppleScriptTask and NSAppleScript are a little tired, mind you. None of them provide automatic data conversion between Cocoa and AS types, which means that many manual deletions with NSAppleEventDescriptors pass parameters and results. Partial support is provided on NSAppleScript instances: the script properties retain state for calls to several handlers, but there is no way to save the changed script back to disk so that any changes are lost after it is released. And NSUSerAppleScriptTask is strictly one-time, so the state of the script is not saved between calls.

For deeper integration between AppleScript and ObjC embedded code in your application bundle, use AppleScriptObjC (10.6 +):

ASOC is a two-way bridge, similar to PyObjC or RubyCocoa, allowing you to write AppleScript code inside script objects, which are then displayed in ObjC code as regular Cocoa classes, allowing ObjC code to call AS handlers and AS code to call ObjC methods. The common types ObjC and AS (ints, doubles, NSStrings, NSArrays, etc.) are automatically wrapped / converted when crossing the bridge, so it does not require additional work, another random transmission on the AS side.

ASOC is not ideal (Apple sucks with its documents, bridges are not free, and glitches are not unknown), but for interacting with ObjC scripted applications this is the best alternative choice of garbage.

+11
source

Why not put your compiled script text or script into your package, and then use NSAppleScript initWithContentsOfURL: error: method ?

For instance:

 NSError * error = NULL; NSURL * resourceURL = [[NSBundle mainBundle] resourceURL]; NSURL * urlOfScript = [resourceURL URLByAppendingPathComponent: @"MyApplescript.scpt"]; NSAppleScript *script = [[NSAppleScript alloc] initWithContentsOfURL: urlOfScript error: &error]; if(script == NULL) { NSLog( @"could not instantiate script at %@ - %@", [urlOfScript absolutePath], [error localizedDescription] ); } 
+2
source

Source: https://habr.com/ru/post/944797/


All Articles