Skip to content

Instantly share code, notes, and snippets.

@VishwaiOSDev
Created October 15, 2025 04:02
Show Gist options
  • Select an option

  • Save VishwaiOSDev/2dbebed28a736d65208e2b28bd82e990 to your computer and use it in GitHub Desktop.

Select an option

Save VishwaiOSDev/2dbebed28a736d65208e2b28bd82e990 to your computer and use it in GitHub Desktop.
Swift to create or generate a thumbnail image from a video url using AVFoundation.
import AVFoundation
import UIKit
import SwiftUI
/// Generates a thumbnail (UIImage) from a video URL asynchronously.
func generateThumbnail(for url: URL, at time: Double = 0.0) async -> UIImage? {
let asset = AVURLAsset(url: url)
let generator = AVAssetImageGenerator(asset: asset)
// Ensures the thumbnail has the correct orientation
generator.appliesPreferredTrackTransform = true
// CMTime specifies the time in the video to capture a frame.
// We use a preferred timescale of 600 for high precision.
let timestamp = CMTime(seconds: time, preferredTimescale: 600)
do {
// Use the async 'image(at:)' method to generate the CGImage
let imageRef = try await generator.image(at: timestamp).image
return UIImage(cgImage: imageRef)
} catch {
print("Error generating thumbnail for \(url): \(error)")
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment