Swift AVAssetExportSession export from .mov to .mp4 : The operation could not be completed

114 Views Asked by At

I'm struggling to export a .mov file from the photo library as a .mp4 and upload it to a server.

Im using a PHPickerViewController on a swiftUI view to pick the video file.

result.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier) { url, error in
    print("\(url)")                                    
}

url prints as file:///private/var/mobile/Containers/Data/Application/XXXX-XXXXX-XXXX/tmp/.com.apple.Foundation.NSItemProvider.MJGgiJ/IMG_3725.mov

This url exported as a .mp4 which fails with Exporting failed from below code. error description The operation could not be completed

let asset = AVAsset(url: url)
fileName = "output_" + fileName
let outputMovieURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent(fileName)
         
let renderSize = CGSize(width: 640, height: 480)
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = renderSize
videoComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
            
let videoInstruction = AVMutableVideoCompositionInstruction()
videoInstruction.timeRange = CMTimeRange(start: CMTime.zero, duration: asset.duration)

videoComposition.instructions = [videoInstruction]

            
let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)
            
exporter?.videoComposition = videoComposition
exporter?.outputURL = outputMovieURL!
exporter?.outputFileType = .mp4
exporter?.shouldOptimizeForNetworkUse = true
exporter?.exportAsynchronously(completionHandler: { [weak exporter] in
                
switch (exporter?.status) {
case .cancelled:
     print("Exporting cancelled");
case .completed:
     print("Exporting completed");
case .exporting:
     print("Exporting ...");
case .failed:
     print("Exporting failed");
default:
    print("Exporting with other result");
}
                
if let error = exporter?.error {
    print("export failed \(error.localizedDescription)")
    completion(nil)
} else {
    print("exported file saved at \(outputMovieURL)")
    completion(outputMovieURL)
}
                

I am testing this on a real device (iPhone 12) running iOS 16.3.1. Project deployment target is iOS 16.

Am i doing anything wrong? Any help would be much appreciated!

0

There are 0 best solutions below