Grab frames from video using Swift

For swift 4.2

fileprivate func generateThumnail(url : URL, fromTime:Float64) -> UIImage? {
    let asset :AVAsset = AVAsset(url: url)
    let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
    assetImgGenerate.appliesPreferredTrackTransform = true
    assetImgGenerate.requestedTimeToleranceAfter = CMTime.zero;
    assetImgGenerate.requestedTimeToleranceBefore = CMTime.zero;
    let time : CMTime = CMTimeMakeWithSeconds(fromTime, preferredTimescale: 600)
    if let img = try? assetImgGenerate.copyCGImage(at:time, actualTime: nil) {
        return UIImage(cgImage: img)
    } else {
        return nil
    }
}

I incorporated arpo's answer into my project, updated for Swift 3:

fileprivate func generateThumnail(url : URL, fromTime:Float64) -> UIImage? {
    let asset :AVAsset = AVAsset(url: url)
    let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
    assetImgGenerate.appliesPreferredTrackTransform = true
    assetImgGenerate.requestedTimeToleranceAfter = kCMTimeZero;
    assetImgGenerate.requestedTimeToleranceBefore = kCMTimeZero;
    let time        : CMTime = CMTimeMakeWithSeconds(fromTime, 600)
    if let img = try? assetImgGenerate.copyCGImage(at:time, actualTime: nil) {
        return UIImage(cgImage: img!)
    } else {
        return nil
    }
}

Thanks to @eric-d who found this post: iOS Take Multiple Screen Shots

I manage to find out that adding:

    assetImgGenerate.requestedTimeToleranceAfter = kCMTimeZero;
    assetImgGenerate.requestedTimeToleranceBefore = kCMTimeZero;

...to my function will do the trick.

My updated function looks like this:

func generateThumnail(url : NSURL, fromTime:Float64) -> UIImage {
    var asset :AVAsset = AVAsset.assetWithURL(url) as! AVAsset
    var assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
    assetImgGenerate.appliesPreferredTrackTransform = true
    assetImgGenerate.requestedTimeToleranceAfter = kCMTimeZero;
    assetImgGenerate.requestedTimeToleranceBefore = kCMTimeZero;
    var error       : NSError? = nil
    var time        : CMTime = CMTimeMakeWithSeconds(fromTime, 600)        
    var img         : CGImageRef = assetImgGenerate.copyCGImageAtTime(time, actualTime: nil, error: &error)
    var frameImg    : UIImage = UIImage(CGImage: img)!
    return frameImg
}

var grabTime = 1.22
img = generateThumnail(urlVideo, fromTime: Float64(grabTime))