无法生成视频iOS swift的缩略图

时间:2018-01-22 18:53:25

标签: ios swift uiimagepickercontroller

我正在尝试为使用imagePicker选择的视频生成缩略图,但我收到此错误

  "[discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled"

UserInfo = {NSLocalizedDescription =查询已取消} “,有人可以帮我找出原因吗?

下面是我的代码中的一些代码段。

let imagePickerController = UIImagePickerController()
var videoURL: NSURL?
@IBOutlet weak var videoImageTemp: UIImageView!

此函数用于启动实例化imagePickerController

的过程
@IBAction func addVideo(_ sender: Any) {

    imagePickerController.sourceType = .photoLibrary
    imagePickerController.delegate = self
    imagePickerController.mediaTypes = ["public.movie"]

    present(imagePickerController, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
     let asset = AVAsset(url: info["UIImagePickerControllerReferenceURL"] as! URL)
        let assetImgGenerate : AVAssetImageGenerator = AVAssetImageGenerator(asset: asset)
        assetImgGenerate.appliesPreferredTrackTransform = true
        let time = CMTimeMake(1, 2)
        let img = try? assetImgGenerate.copyCGImage(at: time, actualTime: nil)
        if img != nil {
            let frameImg  = UIImage(cgImage: img!)
                self.videoImageTemp.image = frameImg
                self.videoImageTemp.contentMode = .scaleAspectFit
                // assign your image to UIImageView
    }
    imagePickerController.dismiss(animated: true, completion: nil)
}

1 个答案:

答案 0 :(得分:1)

您的视频网址是一个临时文件网址。一旦didFinishPickingMediaWithInfo方法完成,该文件将被删除。 BTW与你的问题没有关系,但你应该使用URL而不是NSREL自Swift 3.你需要在didFinishPickingMediaWithInfo method内的主线程中执行它,更改previewImageFromVideo方法声明并使其同步返回结果图像让它抛出func previewImageFromVideo(url: URL) throws -> CGImage。您的代码应如下所示:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if #available(iOS 11.0, *) {
        if let url = info[UIImagePickerControllerMediaURL] as? URL {
            imageView.image = getVideoThumbFrom(url: url)
        }
    } else {
        if let url = info[UIImagePickerControllerReferenceURL] as? URL {
            imageView.image = getVideoThumbFrom(url: url)
        }
    }
    dismiss(animated: true) {
        print("picker dismissed")
    }
}
func getVideoThumbFrom(url: URL) -> UIImage? {
    do {
        return try UIImage(cgImage: previewImageFromVideo(url: url))
    } catch {
        print(error)
        return nil
    }
}
func previewImageFromVideo(url: URL) throws -> CGImage {
    let imageGenerator = AVAssetImageGenerator(asset: AVAsset(url: url))
    imageGenerator.appliesPreferredTrackTransform = true
    return try imageGenerator.copyCGImage(at: CMTimeMake(1, 2), actualTime: nil)
}

Sample project