Brad Brad - 9 months ago 43
Swift Question

How to save a video from AVAssetExportSession to Camera Roll?

I have some code that edits a video, and then creates an AVAssetExportSession to save the edited video somewhere. I would like to save it to the camera roll, but can't figure out what the NSURL for that is.

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


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

Answer Source

You can't save your video directly to the camera roll simply by using session.outputURL = .... You'll have to save the video to a file path (temporary or otherwise) then write the video at that url to your camera roll using writeVideoAtPathToSavedPhotosAlbum:, ex:

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
        // ...
    })
})