Search code examples
iosswift

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?


Solution

  • 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
        }
    }