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?
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
}
}
Here's SWIFT 3.0 using extension
import Foundation
import UIKit
import MediaPlayer
import SystemConfiguration
extension AVAsset{
var videoThumbnail:UIImage?{
let assetImageGenerator = AVAssetImageGenerator(asset: self)
assetImageGenerator.appliesPreferredTrackTransform = true
var time = self.duration
time.value = min(time.value, 2)
do {
let imageRef = try assetImageGenerator.copyCGImage(at: time, actualTime: nil)
let thumbNail = UIImage.init(cgImage: imageRef)
print("Video Thumbnail genertated successfuly".DubugSuccess())
return thumbNail
} catch {
print("error getting thumbnail video".DubugError(),error.localizedDescription)
return nil
}
}
}
Then simply from anywhere you have access to AVAsset/URL:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if let videoURL = info[UIImagePickerControllerMediaURL] as? NSURL {
let video = NSData(contentsOfURL: videoURL)
//Create AVAsset from url
let ass = AVAsset(url:videoURL)
if let videoThumbnail = ass.videoThumbnail{
print("Success")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With