Charles Panel Charles Panel - 2 months ago 14x
Swift Question

Where does the object created by this Swift function go?

I am looking at this branch on GitHub:

This is the function, used to create a GIF from UIImages in Swift:

func createGIF(with images: [UIImage], loopCount: Int = 0, frameDelay: Double, callback: (data: NSData?, error: NSError?) -> ()) {
let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: loopCount]]
let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: frameDelay]]

let documentsDirectory = NSTemporaryDirectory()
let url = NSURL(fileURLWithPath: documentsDirectory)?.URLByAppendingPathComponent("animated.gif")

if let url = url {
let destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, UInt(images.count), nil)
CGImageDestinationSetProperties(destination, fileProperties)

for i in 0..<images.count {
CGImageDestinationAddImage(destination, images[i].CGImage, frameProperties)

if CGImageDestinationFinalize(destination) {
callback(data: NSData(contentsOfURL: url), error: nil)
} else {
callback(data: nil, error: NSError())
} else {
callback(data: nil, error: NSError())

I am not sure I understand what is going on. Shouldn't the function return an object to be used? Where does the created GIF go? Is it possible to use it in other parts of my code, for instance to put it in a UIImageView, or UIImage?

Thank you


The result GIF is passed as NSData into the callback then you can create your NSImage from it. Note that the same callback is used in error conditions - then data is nil and error is not.