illustrative abstractions

0%

Swift Thumbnail on the fly

Description

It is quite painful where you have a decent video API, but doesn’t provide you with a thumbnail. This makes it very hard to demonstrate to users what the video looks like a first glance.

Therefore, we have came up with a technique that buffers the first minute of a video and generate a thumbnail on the fly.

Code

Using AVAsset, we can write an extension that dispatches a thread dedicated to generate a thumbnail (also duration of the video in the case below).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
extension AVAsset {
func generateThumbnail(completion: @escaping (UIImage?, Int?) -> Void) {
DispatchQueue.global().async {
let imageGenerator = AVAssetImageGenerator(asset: self)
let time = CMTime(seconds: 60.0, preferredTimescale: 600)
let times = [NSValue(time: time)]
let duration = Int(self.duration.seconds)
imageGenerator.generateCGImagesAsynchronously(forTimes: times, completionHandler: { _, image, _, _, _ in
if let image = image {
completion(UIImage(cgImage: image), duration)
} else {
completion(nil, nil)
}
})
}
}
}

More

For more information, checkout

  • AVAsset - AVFoundation | Apple Developer Documentation
  • Generate images from AVAsset with AVAssetImageGenerator