After reading several tutorials like this and looking at other code exporting videos, we still can't resolve an issue.
Sometimes a new video gets exported to the Camera Roll, and sometimes it doesn't. We can't even reproduce the problem consistently.
The only issue we can imagine is if NSFileManager.defaultManager().removeItemAtPath
is not a blocking call, but no documentation suggests it's asynchronous, so we assume it's not the case.
Each time, the "Saved video" println
inside the writeVideoAtPathToSavedPhotosAlbum
closure gets called, suggesting the video was successfully written to the Camera Roll, but we don't see the video there.
Suggestions on how to troubleshoot?
Code:
// -- Get path
let fileName = "/editedVideo.mp4"
let allPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docsPath = allPaths[0] as! NSString
let exportPath = docsPath.stringByAppendingFormat(fileName)
let exportUrl = NSURL.fileURLWithPath(exportPath as String)!
println(exportPath)
// -- Remove old video?
if NSFileManager.defaultManager().fileExistsAtPath(exportPath as String) {
println("Deleting existing file\n")
NSFileManager.defaultManager().removeItemAtPath(exportPath as String, error: nil)
}
// -- Create exporter
let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
exporter.videoComposition = mutableComposition
exporter.outputFileType = AVFileTypeMPEG4
exporter.outputURL = exportUrl
exporter.shouldOptimizeForNetworkUse = true
// -- Export video
exporter.exportAsynchronouslyWithCompletionHandler({
self.exportDidFinish(exporter)
})
}
func exportDidFinish(exporter: AVAssetExportSession) {
println("Finished exporting video!")
// Write out video to photo album
let assetLibrary = ALAssetsLibrary()
assetLibrary.writeVideoAtPathToSavedPhotosAlbum(exporter.outputURL, completionBlock: {(url: NSURL!, error: NSError!) in
println("Saved video \(exporter.outputURL)")
if (error != nil) {
println("Error saving video")
}
})
}
A few suggestion that may help resolve your issue:
Check that the video is valid/compatible with the library as done here
ensure that the asset url passed back is not nil as referenced here
consider using the PHPhotoLibrary instead for exporting video