adriankhan
adriankhan

Reputation: 59

How to save AVMutableComposition (directly) without AVMutableVideoComposition to camera roll/gallery/photos - Swift 5

I am one step away from finishing my first original app so I'm quite desperate for an answer.

I have created an AVMutableComposition (not AVMutableVideoComposition) that combines multiple clips. All I want to do is save it to camera roll or gallery. The only way I know how to do so is using AVMutableVideoComposition but in my current situation that would take a really long time because of the way I structured my app. I have also used PHPhotoLibrary but that only applies to URL videos. (is there a way to convert AVMutableComposition's to URL's?)

Here's what I've tried that doesn't work:

var mixComposition = AVMutableComposition() //trying to save this

  func saveToGallery() {
        let savePathUrl: URL = URL(fileURLWithPath: NSHomeDirectory() + "/Documents/newVideo.mp4")
        do { 
            try FileManager.default.removeItem(at: savePathUrl)
        } catch { print(error.localizedDescription) }

        let assetExport: AVAssetExportSession = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)!
        assetExport.outputFileType = AVFileType.mp4
        assetExport.outputURL = savePathUrl
        assetExport.shouldOptimizeForNetworkUse = true

        assetExport.exportAsynchronously { () -> Void in
            switch assetExport.status {
            case AVAssetExportSessionStatus.completed:
                print("successfully saved")  // but it still prints this 
                
            case AVAssetExportSessionStatus.failed:
                print("failed")
                
            case AVAssetExportSessionStatus.cancelled:
                print("cancelled")
                
            default:
                print("complete")
                
            }
        }
    }

  @IBAction func SaveButtonDidTouch(_ sender: Any) {

        saveToGallery() //??
        
    }

It still prints "successfully saved" even though nothing is added to my gallery/camera roll.

So what is the most efficient way to save an AVMutableComposition? Where did I go wrong here?

Upvotes: 1

Views: 434

Answers (0)

Related Questions