swiftdocumentsvideo-thumbnails

Document file path unreachable in swift


I'm currently working on a small swift application and I'm storing some video records in the documents folder of the app. I would like to retrieve these on a later moment. I already got an array of file locations like this:

file:///private/var/mobile/Containers/Data/Application/6C462C4E-05E2-436F-B2E6-F6D9AAAC9361/Documents/videorecords/196F9A75-28C4-4B65-A06B-6111AEF85F01.mov

Now I want to use such file location to create a thumbnail with the first frame and connect that to my imageview with the following piece of code:

func createVideoStills() {
    for video in directoryContents {
        print("\(video)")
        do {
            let asset = AVURLAsset(URL: NSURL(fileURLWithPath: "\(video)"), options: nil)
            let imgGenerator = AVAssetImageGenerator(asset: asset)
            imgGenerator.appliesPreferredTrackTransform = true
            let cgImage = try imgGenerator.copyCGImageAtTime(CMTimeMake(0, 1), actualTime: nil)
            let uiImage = UIImage(CGImage: cgImage)
            videoCell.imageView = UIImageView(image: uiImage)
            //let imageView = UIImageView(image: uiImage)
        } catch let error as NSError {
            print("Error generating thumbnail: \(error)")
        }
    }
}

The first print gives me a path like described above. But the AVURLAsset doesn't like this path because it spits out the following error:

Error generating thumbnail: Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." UserInfo={NSLocalizedDescription=The requested URL was not found on this server., NSUnderlyingError=0x14ee29170 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

Which is weird cause it is right there. Any solutions on how to fix/solve this?

Kind regards,

Wouter


Solution

  • The output of your print("\(video)") is not a file path but a string representation of file URL. You need to use init(string:) than init(fileURLWithPath:) of NSURL.

    See what you get with:

                let asset = AVURLAsset(URL: NSURL(string: video), options: nil)
    

    (Unnecessary string interpolation would generate some unexpected result without errors -- like getting "Optional(...)", so you should avoid.)