Reza Khonsari
Reza Khonsari

Reputation: 466

Swift - AVAssetExportSession exportSession.exportAsynchronously completion handler not called

I used this link and following code in my project but AVAssetExportSession - exportAsynchronously method completion handler doesn't called in my project:

StackLink

func encodeVideo(at videoURL: URL, completionHandler: ((URL?, Error?) -> ())?)  {
        let avAsset = AVURLAsset(url: videoURL, options: nil)
        
        let startDate = Date()
        
        //Create Export session
        guard let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetPassthrough) else {
            completionHandler?(nil, nil)
            return
        }
        
        //Creating temp path to save the converted video
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as URL
        let filePath = documentsDirectory.appendingPathComponent("rendered-Video.mp4")
        
        //Check if the file already exists then remove the previous file
        if FileManager.default.fileExists(atPath: filePath.path) {
            do {
                try FileManager.default.removeItem(at: filePath)
            } catch {
                completionHandler?(nil, error)
            }
        }
        
        exportSession.outputURL = filePath
        exportSession.outputFileType = .mp4
        exportSession.shouldOptimizeForNetworkUse = true
        let start = CMTimeMakeWithSeconds(0.0, preferredTimescale: 0)
        let range = CMTimeRangeMake(start: start, duration: avAsset.duration)
        exportSession.timeRange = range
        
        exportSession.exportAsynchronously {
            switch exportSession.status {
            case .failed:
                print(exportSession.error ?? "NO ERROR")
                completionHandler?(nil, exportSession.error)
            case .cancelled:
                print("Export canceled")
                completionHandler?(nil, nil)
            case .completed:
                //Video conversion finished
                let endDate = Date()
                
                let time = endDate.timeIntervalSince(startDate)
                print(time)
                print("Successful!")
                print(exportSession.outputURL ?? "NO OUTPUT URL")
                completionHandler?(exportSession.outputURL, nil)
            case .unknown:
                print("Export Unknown Error")
            default: break
            }
            
        }
    }

I also share my project on GitHub that you can check it,
thanks

GitRepo

I use Xcode 12.3

Upvotes: 2

Views: 1617

Answers (1)

Reza Khonsari
Reza Khonsari

Reputation: 466

It is an iOS bug. Even screen recording on my iOS device doesn't work, after I get into this bug. I restarted my phone and everything goes fine but this takes me some times to understand the solution.

I'm using iOS 14.3

Upvotes: 10

Related Questions