Skip to content

Instantly share code, notes, and snippets.

@phuochau
Forked from bomberstudios/README.md
Created October 23, 2017 13:04
Show Gist options
  • Save phuochau/772995373d537642e49f09cf87256a27 to your computer and use it in GitHub Desktop.
Save phuochau/772995373d537642e49f09cf87256a27 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