Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a video from AVAssetExportSession to Camera Roll?

Tags:

ios

swift

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.

like image 936
Brad Avatar asked Mar 11 '15 01:03

Brad


2 Answers

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
        // ...
    })
})
like image 106
Lyndsey Scott Avatar answered Oct 21 '22 03:10

Lyndsey Scott


Here is a cleaned up answer for Swift 3 that now saves to the album via the Photos framework.

You will need to import both AVFoundation and Photos for this to work.

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")
            }
        }
    })
}
like image 34
CodeBender Avatar answered Oct 21 '22 02:10

CodeBender