AVAssetImageGeneratorCompletionHandler and Swift

Posting this here for my own probable future reference.

I’m picking up Swift in small bursts. Usually where I have a small screen that doesn’t rely on any of the Objective C based library I have within GoVJ.

I had a UITableViewController that I wanted to load thumbnails into from a collection of videos held as an array of AVAssets.

// Configure the cell

let assetUrl = demoContent.objectAtIndex(indexPath.row) as! NSURL
let asset: AVAsset = AVAsset(URL:assetUrl) as AVAsset
let imageGenerator = AVAssetImageGenerator(asset: asset);
imageGenerator.maximumSize = CGSize(width: 640,height: 480)
imageGenerator.apertureMode = AVAssetImageGeneratorApertureModeProductionAperture;

imageGenerator.appliesPreferredTrackTransform = true;

imageGenerator.requestedTimeToleranceAfter = kCMTimeZero

imageGenerator.requestedTimeToleranceBefore = kCMTimeZero

So far so good, everything is basically the same as Objective C.

I then create a CMTime value, that refers to the middle of the video file;

// Create thumbNail at middle of loop

let tVal = NSValue(CMTime: CMTimeMultiplyByFloat64(asset.duration, 0.5))

I then call generateCGImagesAsynchronouslyForTimes. I want to be able to chuck my thumbNail setting code into it’s block handler. This is fairly straight forwards in objective C, and I understand what I’m doing there in creating the block.

However Swift’s block formation eluded me, in particular the way ‘in’ follows the parameters and then you type the code you want to execute.

This is what I have now to set my thumbNails:

imageGenerator.generateCGImagesAsynchronouslyForTimes([tVal], completionHandler: {(_, im:CGImage?, _, _, e:NSError?) in 

if let img = im {
dispatch_async(dispatch_get_main_queue()) {
cell.demoContentThumbNail.image = UIImage(CGImage: img)
} else {
print("failed in generating thumbnail")

return cell