Charles Panel Charles Panel - 3 months ago 26
Swift Question

Where does the object created by this Swift function go?

I am looking at this branch on GitHub:

https://gist.github.com/westerlund/eae8ec71cdac88be7c3a

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

Answer

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.