How to save video from AVAssetExportSession in Camera Roll?

I have a code that edits a video and then creates an AVAssetExportSession to save the edited video somewhere. I would like to keep it in a camera roll, but I can not understand what NSURL is.

var session: AVAssetExportSession = AVAssetExportSession(asset: myasset, presetName: AVAssetExportPresetHighestQuality) session.outputURL = ??? session.exportAsynchronouslyWithCompletionHandler(nil) 

Does anyone know how to determine the correct NSURL to save video to camera roll? Thanks in advance for your help.

+6
source share
2 answers

You cannot save your video directly to the camera roll, simply using session.outputURL = ... You will need to save the video in the file path (temporary or different), and then record the video with this URL into your camera frame using writeVideoAtPathToSavedPhotosAlbum: for example:

 var exportPath: NSString = NSTemporaryDirectory().stringByAppendingFormat("/video.mov") var exportUrl: NSURL = NSURL.fileURLWithPath(exportPath)! var exporter = AVAssetExportSession(asset: myasset, presetName: AVAssetExportPresetHighestQuality) exporter.outputURL = exportUrl exporter.exportAsynchronouslyWithCompletionHandler({ let library = ALAssetsLibrary() library.writeVideoAtPathToSavedPhotosAlbum(exportURL, completionBlock: { (assetURL:NSURL!, error:NSError?) -> Void in // ... }) }) 
+10
source

Below is the cleared answer for Swift 3 , which is now saved in the album through the Photos framework.

To do this, you need to import both AVFoundation and Photos .

 func exportAsset(asset: AVAsset) { let exportPath = NSTemporaryDirectory().appendingFormat("/video.mov") let exportURL = URL(fileURLWithPath: exportPath) let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) exporter?.outputURL = exportURL exporter?.exportAsynchronously(completionHandler: { PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: exportURL) }) { saved, error in if saved { print("Saved") } } }) } 
+3
source

Source: https://habr.com/ru/post/983622/


All Articles