Bartłomiej Semańczyk Bartłomiej Semańczyk - 5 months ago 67
Swift Question

How to get thumbnail image of video picked from UIPickerViewController in Swift?

This is how I access the video:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {

if let videoURL = info[UIImagePickerControllerMediaURL] as? NSURL {
let video = NSData(contentsOfURL: videoURL)
}
}


That
video
I would like to show the user in my controller (I do not mean
UIDocumentInteractionController
to preview this). I need a thumbnail of that video, and then assign this to
UIImageView
. Is it possible?

Answer

The simplest answer:

import AVFoundation

private func thumbnailForVideoAtURL(url: NSURL) -> UIImage? {

    let asset = AVAsset(URL: url)
    let assetImageGenerator = AVAssetImageGenerator(asset: asset)

    var time = asset.duration
    time.value = min(time.value, 2)

    do {
        let imageRef = try assetImageGenerator.copyCGImageAtTime(time, actualTime: nil)
        return UIImage(CGImage: imageRef)
    } catch {
        print("error")
        return nil
    }
}
Comments