Skip to content

Instantly share code, notes, and snippets.

@bomberstudios
Last active August 29, 2015 14:22
Show Gist options
  • Save bomberstudios/d88b801bb04e3764e2ff to your computer and use it in GitHub Desktop.
Save bomberstudios/d88b801bb04e3764e2ff to your computer and use it in GitHub Desktop.
Sandbox, we love you (NOT)

I'm running this code here:

var str = @"This is a string"
var path = "/Users/ale/Desktop/test.txt" // edit this, unless your name is awesome

var return1 = [str writeToFile:path atomically:true encoding:NSUTF8StringEncoding error:nil]

log(return1) // 0 if error, 1 if successful

If you run it on a non-sandboxed Sketch, Console.app will output this:

09/06/15 21:43:56,664 untitled script (Sketch Plugin)[2862]: 1

and the .txt file will be created.

However, if you run that on a sandboxed Sketch, Console.app will output this:

09/06/15 21:43:51,185 untitled script (Sketch Plugin)[2808]: 0
09/06/15 21:43:51,205 sandboxd[317]: ([2808]) Sketch (2808) deny file-write-unlink /Users/ale/Desktop/test.txt

and the .txt file will not be created.

A sandboxed app has limited access to files and folders (see Apple's documentation for the complete reference). One of the folders you can use is a temporary folder. We'll create one using this code here:

function temp_folder(){

  globallyUniqueString = [[NSProcessInfo processInfo] globallyUniqueString];
  tempDirectoryPath = NSTemporaryDirectory()
  tempDirectoryPath = [tempDirectoryPath stringByAppendingPathComponent:globallyUniqueString];
  tempDirectoryURL = [NSURL fileURLWithPath:tempDirectoryPath isDirectory:true];
  [[NSFileManager defaultManager] createDirectoryAtURL:tempDirectoryURL withIntermediateDirectories:true attributes:nil error:nil];

  return tempDirectoryPath;
}

var str = @"This is a string"
var path = temp_folder() + "/file.txt"
log(path)

var return1 = [str writeToFile:path atomically:true encoding:NSUTF8StringEncoding error:nil]

log(return1) // 0 if error, 1 if successful

If you run that, a file will be created in a temporary folder (something with a path similar to:

/var/folders/9x/k1std1rj03n5tlq0wtlgtvwr0000gn/T/com.bohemiancoding.sketch3/EB8D5674-7994-4A3D-9ECC-DF081BD6986B-2808-00001C7249922E1A/file.txt

The other options in the docs either require modifications to the sandboxed app's code (i.e: extra entitlements) or require you to ask the user for permission for each save (see https://github.com/bomberstudios/sketch-sandbox for an example, altough the code has never worked reliably)

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