Generating Video Thumbnails with AVAssetImageGenerator
AVFoundation usage plus async UI hygiene.
load AVAsset, configure AVAssetImageGenerator, request the time off the main thread, hop back to update UI.
doing the decode synchronously on the main thread.
WHAT THIS TESTS This checks AVFoundation familiarity and, just as importantly, whether you keep heavy decoding work off the main thread so the UI stays responsive.
A GOOD ANSWER COVERS Create an AVAsset, or AVURLAsset, from the video URL. Instantiate an AVAssetImageGenerator with that asset. Set appliesPreferredTrackTransform to true so the thumbnail respects the video's recorded orientation rather than appearing rotated. Build a CMTime for the target moment, then request the frame asynchronously, on modern OS versions using the async image(at:) method or generateCGImagesAsynchronously, which delivers results on a background queue. Wrap the resulting CGImage in a UIImage and dispatch UI updates to the main queue.
COMMON WRONG ANSWERS Calling the synchronous copyCGImage on the main thread, which decodes a frame and stalls scrolling. Forgetting appliesPreferredTrackTransform, yielding sideways thumbnails. Decoding a full-resolution frame for a tiny image view, wasting memory and CPU.
LIKELY FOLLOW-UPS How do requestedTimeToleranceBefore and after trade accuracy for speed by snapping to keyframes? How do you set maximumSize to downscale during decode? How would you cancel pending requests when a cell is reused in a collection view? How do you cache generated thumbnails to avoid redundant work?
ONE CONCRETE EXAMPLE For a video feed, each cell asks a thumbnail service for a frame. The service creates an AVAssetImageGenerator, sets maximumSize to roughly the cell's pixel size and tolerances of a fraction of a second so it lands on a nearby keyframe quickly, then requests the image asynchronously. When the cell is reused before the result arrives, the service cancels the outstanding generation. On completion it hops to the main queue, sets the cell's image, and stores it in an in-memory cache keyed by URL and time so the next scroll back is instant.
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.