Skip to content

Instantly share code, notes, and snippets.

@rborn
Forked from bomberstudios/README.md
Created January 26, 2017 15:16
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 rborn/814d494be7194c127855cd8548108d51 to your computer and use it in GitHub Desktop.
Save rborn/814d494be7194c127855cd8548108d51 to your computer and use it in GitHub Desktop.
Loading a Cocoa Framework in a Sketch Plugin

This is what Craft does:

function loadFramework(pluginRoot) {
  if (NSClassFromString('PanelsManager') == null) {
    var mocha = [Mocha sharedRuntime];
    return [mocha loadFrameworkWithName:'Panels' inDirectory:pluginRoot];
  } else {
    return true;
  }
}

var scriptPath = context.scriptPath;
var pluginRoot = [scriptPath stringByDeletingLastPathComponent];
loadFramework(pluginRoot);
[[PanelsManager sharedManager] load];

They took that code from Avocode's plugin, which does this:

var pluginRoot = sketch.scriptPath.stringByDeletingLastPathComponent();

loadFramework(pluginRoot);

[Avocode load];
var avocode = [[Avocode alloc] init];
[avocode export:pluginRoot];

function loadFramework(pluginRoot) {
  if (NSClassFromString('Avocode') == null) {
    var mocha = [Mocha sharedRuntime];
    return [mocha loadFrameworkWithName:"AvocodeExporter" inDirectory:pluginRoot + "/avocode-exporter"];
  } else {
    return true;
  }
}

Basically, you use Mocha to load the Framework, and then either the Framework takes control, or you just access it from CocoaScript like you do with other Cocoa objects.

Caveats: not all Frameworks can be used in this way. If you need to use Obj-C blocks to use the Framework, CocoaScript doesn't support them. If you need to use delegates, take a look at MochaJSDelegate.

Alternatively, you may want to use an external app to process your data. There's a nice example of how to do that here: https://github.com/abynim/Sketch-PluginHelper

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment