Code for solution that uses AVFoundation
framework and Swift 3.0 (commented code isn't necessary and is discussed below the code - you have to decide whether you need it or not):
import AVFoundation
func generateThumbnailForVideo(at url: URL) -> UIImage? {
let kPreferredTimescale: Int32 = 1000
let asset = AVURLAsset(url: url)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true
//generator.requestedTimeToleranceBefore = kCMTimeZero
//generator.requestedTimeToleranceAfter = kCMTimeZero
//generator.maximumSize = CGSize(width: 100, height: 100)
var actualTime: CMTime = CMTime(seconds: 0, preferredTimescale: kPreferredTimescale)
//generates thumbnail at first second of the video
let cgImage = try? generator.copyCGImage(at: CMTime(seconds: 1, preferredTimescale: kPreferredTimescale), actualTime: &actualTime)
return cgImage.flatMap() { return UIImage(cgImage: $0, scale: UIScreen.main.scale, orientation: .up) }
}
Note that you may consider running this code on background thread as thumbnail creation can be potentially a costly operation.
Also, please take a look at some of the properties of AVAssetImageGenerator
class:
requestedTimeToleranceBefore
(Apple's documentation):
The maximum length of time before a requested time for which an image may be generated.
The default value is kCMTimePositiveInfinity.
Set the values of requestedTimeToleranceBefore and requestedTimeToleranceAfter to kCMTimeZero to request frame-accurate image generation; this may incur additional decoding delay.
requestedTimeToleranceAfter
(Apple's documentation):
The maximum length of time after a requested time for which an image may be generated.
The default value is kCMTimePositiveInfinity.
Set the values of requestedTimeToleranceBefore and requestedTimeToleranceAfter to kCMTimeZero to request frame-accurate image generation; this may incur additional decoding delay.
maximumSize
(Apple's documentation):
Specifies the maximum dimensions for generated image.
The default value is CGSizeZero, which specifies the asset’s unscaled dimensions.
AVAssetImageGenerator scales images such that they fit within the defined bounding box. Images are never scaled up. The aspect ratio of the scaled image is defined by the apertureMode property.