I am trying to save both the recorded path to the video file and the thumbnail from the video to the document directory. Then set these two values to the object using the file paths so that I can use the object to populate the collection view. With the code that I currently have (below), after recording the video, the path to the video is saved in the document directory, and the path to the video and thumbnail is set to my object Post
, and the thumbnail is displayed correctly in my collection view. Everything is fine so far .
However, only the video path is saved between application restarts, since it is in the directory, but the thumbnail is not. I would also like to save the sketch, but I do not know how to do this, since it seems that you can only write URLs to a directory.
This is my first experience using a document catalog, so any help would be appreciated! How can I write a thumbnail (UIImage) in a document directory with a video?
Here is my code:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
dismiss(animated: true, completion: nil)
if mediaType == kUTTypeMovie {
var uniqueVideoID = ""
var videoURL:NSURL? = NSURL()
var uniqueID = ""
uniqueID = NSUUID().uuidString
videoURL = info[UIImagePickerControllerMediaURL] as? URL as NSURL?
let myVideoVarData = try! Data(contentsOf: videoURL! as URL)
let docPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentsDirectory: AnyObject = docPaths[0] as AnyObject
uniqueVideoID = uniqueID + "VIDEO.MOV"
let docDataPath = documentsDirectory.appendingPathComponent(uniqueVideoID) as String
try? myVideoVarData.write(to: URL(fileURLWithPath: docDataPath), options: [])
print("docDataPath under picker ", docDataPath)
print("Video saved to documents directory")
let asset = AVAsset(url: URL(fileURLWithPath: docDataPath))
let assetImageGenerate = AVAssetImageGenerator(asset: asset)
assetImageGenerate.appliesPreferredTrackTransform = true
let time = CMTimeMake(asset.duration.value / 3, asset.duration.timescale)
if let videoImage = try? assetImageGenerate.copyCGImage(at: time, actualTime: nil) {
let video = Post(pathToVideo: URL(fileURLWithPath: docDataPath), thumbnail: UIImage(cgImage: videoImage))
posts.append(video)
print("Video saved to Post object")
}
}
}
source
share