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.
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
// ...
})
})
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")
}
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With