Was trying to find a way to download an image from a url and use that image as the fill of a layer. Turns out there wasn't much on the topic here so I came up with a little example:
let sketch = require('sketch')
let fiber = require('sketch/async').createFiber()
let doc = sketch.getSelectedDocument()
let selection = doc.selectedLayers.layers[0]
let url = NSURL.URLWithString("https://upload.wikimedia.org/wikipedia/commons/thumb/5/59/Sketch_Logo.svg/1024px-Sketch_Logo.svg.png")
let session = NSURLSession.sharedSession()
let block = __mocha__.createBlock_function('v32@?0@"NSURL"8@"NSURLResponse"16@"NSError"24', (url,response,error) => {
try {
if (!error) {
let data = NSData.dataWithContentsOfURL(url)
selection.style.fills[0].fillType = 'Pattern'
selection.style.fills[0].pattern.patternType = 'Fit'
selection.style.fills[0].pattern.image = data
} else {
console.log(error)
}
} catch(e) {
console.log(e)
}
fiber.cleanup()
}
))
let downloadTask = session.downloadTaskWithURL_completionHandler(url,block)
downloadTask.resume()
Couple of notes
- Be extra careful with code inside your block. It can be very easy to crash Sketch if any of your code fails. Be sure to wrap in
try
/ catch
- Be sure to clean up the fiber when you are done as that can also crash Sketch