2
votes

I'm trying to get video thumbnails with the following code:

let asset = AVAsset(URL: url)
    let imageGenerator = AVAssetImageGenerator(asset: asset)
    imageGenerator.appliesPreferredTrackTransform = true

    do {
        let cgImage = try imgGenerator.copyCGImageAtTime(CMTimeMake(1, 30), actualTime: nil)
        let uiImage = UIImage(CGImage: cgImage)
        imageview.image = uiImage
    }
    catch let error as NSError
    {
        print("Image generation failed with error \(error)")
    }

Sometimes it works and sometime it doesn't showing the following error:

Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x14eab520 {Error Domain=NSOSStatusErrorDomain Code=-12792 "(null)"}, NSLocalizedFailureReason=An unknown error occurred (-12792)}

I have tried to figure out what is Domain=NSOSStatusErrorDomain Code=-12792 but I don't understand how I can get more details about this error code. How can I convert this error code into a string to get relevant information about what this error means?

1
Can you show your url please? - Dharmbir Singh
@DharmbirSingh Can I send it to you in private ? - Sam
I don't have too much time to take it private. It would be great if you put here. - Dharmbir Singh
do you video play in browser? The Error is probably due to use of URLWithString. I think you should use -fileURLWithPath instead of URLWithString. ref : - stackoverflow.com/questions/18699247/… - Nitin Gohel
thanks @NitinGohel The video is located on a server it is not a local video hence the use of URLWithString - Sam

1 Answers

1
votes

I was able to solve this issue by the following approach.

Swift 4.1

func createThumbnailForVideo(atURL videoURL: URL , completion : @escaping (UIImage?)->Void) {
    let asset = AVAsset(url: videoURL)
    let assetImgGenerate = AVAssetImageGenerator(asset: asset)
    assetImgGenerate.appliesPreferredTrackTransform = true
    let time = CMTimeMakeWithSeconds(1, preferredTimescale: 60)
    let times = [NSValue(time: time)]
    assetImgGenerate.generateCGImagesAsynchronously(forTimes: times, completionHandler: {  _, image, _, _, _ in
        if let image = image {
            let uiImage = UIImage(cgImage: image)
            completion(uiImage)
        } else {
            completion(nil)
        }
    })
}

Hope this will help.