Error Saving Video to Camera Roll? [Swift]

2.1k views Asked by At

I have a function that I want to use to save video to the camera roll. For some reason, after I stop the recording, nothing happens? It does not save it to the camera roll or give any errors other than

Error Domain=NSCocoaErrorDomain Code=-1 "(null)"

Here is my code:

@IBAction func record(_ sender: UIButton) {

    if recordingInProgress{
        output.stopRecording()
        recordingLabel.textColor = UIColor.rgb(red: 173, green: 173, blue: 173)
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: self.outputURL as URL)
        }) { saved, error in
            if saved {
                let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
                let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                alertController.addAction(defaultAction)
                self.present(alertController, animated: true, completion: nil)
            }
        }
    }


    else{
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
        let outputPath = "\(documentsPath)/output.mov"
        outputURL = NSURL(fileURLWithPath: outputPath)
        output.startRecording(toOutputFileURL: outputURL as URL!, recordingDelegate: self)
        recordingLabel.textColor = UIColor.rgb(red: 250, green: 3, blue: 33)
    }

    recordingInProgress = !recordingInProgress


}
1

There are 1 answers

0
marcus.ramsden On BEST ANSWER

You are accessing the video file too soon after calling stopRecording. As metioned over here you should only try to use the URL in the capture(_:didFinishRecordingToOutputFileAt:fromConnections:error:) delegate callback because the recording needs to finalise any writing to the file once you have asked for it to be stopped.

You will want to move your photo library call into that delegate method:

func capture(_ captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAt outputFileURL: URL!, fromConnections connections: [Any]!, error: Error!) {
    // PHPhotoLibrary.shared().performChanges...
}