Search code examples
iosswiftxcodeavkit

Get preview image for remote video


I have a link to the video (for example: http://example.com/video.mp4). I need to get the first frame of the video. I use:

func getPreviewImage(_ url: URL) -> UIImage? {
    let asset = AVURLAsset(url: url)
    let generator = AVAssetImageGenerator(asset: asset)
    generator.appliesPreferredTrackTransform = true
    do {
        let cgImage = try generator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
        return UIImage(cgImage: cgImage)
    } catch {
        print(error)
    }
    return nil
}

However, this does not work. I get the following error in the logs:

Code=-1102 "You do not have permission to access the requested resource.

Tell me how to get the first frame?


Solution

  • Try this.

    func getThumbnailImageFromVideoURL(fromUrl url: URL) -> UIImage? {
        let asset: AVAsset = AVAsset(url: url)
        let imageGenerator = AVAssetImageGenerator(asset: asset)
    
        do {
            let thumbnailImage = try imageGenerator.copyCGImage(at: CMTimeMake(value: 1, timescale: 60) , actualTime: nil)
            return UIImage(cgImage: thumbnailImage)
        } catch let error {
            print(error)
        }
    
        return nil
    }