Use fileOutput to save video to photo gallery

My swift code below goal is to record a 5 second video automatically and save it to the photo gallery when the code is built. In func fileOut I assume that is where you save the video to the photo gallery. I dont know what to put in fileOutput. But fileOutPut is required in my code to run. I think I have all the code to do this but I might be missing something else.

             import AVFoundation;import UIKit
          class ViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {
    func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {


     var captureSession = AVCaptureSession()
     var sessionOutput = AVCaptureStillImageOutput()
    var movieOutput = AVCaptureMovieFileOutput()
     var previewLayer = AVCaptureVideoPreviewLayer()

      @IBOutlet var cameraView: UIView!

  override func viewWillAppear(_ animated: Bool) {
self.cameraView = self.view

let devices = AVCaptureDevice.devices(for:
for device in devices {
    if device.position == AVCaptureDevice.Position.front{


            let input = try AVCaptureDeviceInput(device: device )

            if captureSession.canAddInput(input){

                sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecType.jpeg]

                if captureSession.canAddOutput(sessionOutput){


                    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                    previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
                    previewLayer.connection!.videoOrientation = AVCaptureVideoOrientation.portrait

                    previewLayer.position = CGPoint(x: self.cameraView.frame.width / 2, y: self.cameraView.frame.height / 2)
                    previewLayer.bounds = cameraView.frame




                let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
               let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
                let fileURL = documentURL.appendingPathComponent("tempImage.jpg")
                try? FileManager.default.removeItem(at: fileURL)
                movieOutput.startRecording(to: fileURL, recordingDelegate: self)

                let deadlineTime = + .seconds(1)
                DispatchQueue.main.asyncAfter(deadline: deadlineTime) {






    func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
print("FINISHED \(error)")
// save video to camera roll
if error == nil {
    UISaveVideoAtPathToSavedPhotosAlbum(outputFileURL.path!, nil, nil, nil)


@timswift Do you still have issues with this?

This topic was automatically closed after 166 days. New replies are no longer allowed.