Recording a video stops. fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: error :: “No such file.”ios endless video recordingCoreBluetooth Advertising not startingFirebase swift ios login system error Assertion failed/Exec_BAD_INSTRUNCTION (code=EXC_i386_INVOP, subcode=0x0)Update or reload UITableView after completion of delete action on detail viewI keep getting a use unresolved identifier error swifti cant seem to find the size of the file when im recording audioGLKView.display() method sometimes causes crash. EXC_BAD_ACCESSConvert ViewController Code for RTSP to Swift File to Call into View ControllerAVFoundation video recording stops when camera is switched.Why is an iPhone XS getting worse CPU performance when using the camera live than an iPhone 6S Plus?

Trouble understanding the speech of overseas colleagues

Is there a good way to store credentials outside of a password manager?

Implement the Thanos sorting algorithm

Integer addition + constant, is it a group?

Is there a korbon needed for conversion?

Class Action - which options I have?

How do scammers retract money, while you can’t?

Opposite of a diet

Is expanding the research of a group into machine learning as a PhD student risky?

Why Were Madagascar and New Zealand Discovered So Late?

How long to clear the 'suck zone' of a turbofan after start is initiated?

Avoiding estate tax by giving multiple gifts

Why not increase contact surface when reentering the atmosphere?

Do the temporary hit points from the Battlerager barbarian's Reckless Abandon stack if I make multiple attacks on my turn?

How do I find the solutions of the following equation?

Proof of work - lottery approach

Was Spock the First Vulcan in Starfleet?

How did Doctor Strange see the winning outcome in Avengers: Infinity War?

Go Pregnant or Go Home

Is HostGator storing my password in plaintext?

Is it appropriate to ask a job candidate if we can record their interview?

Purchasing a ticket for someone else in another country?

Method to test if a number is a perfect power?

Sort a list by elements of another list



Recording a video stops. fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: error :: “No such file.”


ios endless video recordingCoreBluetooth Advertising not startingFirebase swift ios login system error Assertion failed/Exec_BAD_INSTRUNCTION (code=EXC_i386_INVOP, subcode=0x0)Update or reload UITableView after completion of delete action on detail viewI keep getting a use unresolved identifier error swifti cant seem to find the size of the file when im recording audioGLKView.display() method sometimes causes crash. EXC_BAD_ACCESSConvert ViewController Code for RTSP to Swift File to Call into View ControllerAVFoundation video recording stops when camera is switched.Why is an iPhone XS getting worse CPU performance when using the camera live than an iPhone 6S Plus?













0















I'm facing problem while recording the video.



The flow is like :-



  1. I'll launch my camera screen.

  2. will record a video then will move to create post screen.

  3. This flow works fine for first time. But when I came back to camera from create post screen, and again try to record, It suddenly stops the recording as soon as i start and throws an error " there is no such file".

Any help would be appreciated.
Thanks.



var captureSession: AVCaptureSession?
var capturePhotoOutput: AVCapturePhotoOutput?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
var userSelectedFlashMode: AVCaptureDevice.FlashMode = .off

override func viewDidAppear(_ animated: Bool)
super.viewDidAppear(animated)
captureSession = AVCaptureSession()
captureSession?.beginConfiguration()
let microphone = AVCaptureDevice.default(for: AVMediaType.audio)
do
let micInput = try AVCaptureDeviceInput(device: microphone!)
if (captureSession?.canAddInput(micInput))!
captureSession?.addInput(micInput)

catch
print("SRL Error setting device audio input.")

guard let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back) else
fatalError("No video device found")

do
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession?.addInput(input)
capturePhotoOutput = AVCapturePhotoOutput()
capturePhotoOutput?.isHighResolutionCaptureEnabled = true
captureSession?.addOutput(capturePhotoOutput!)
captureSession?.sessionPreset = .high
movieFileOutput.maxRecordedDuration = CMTimeMake(value: Int64(59), timescale: 1)
if (captureSession?.canAddOutput(movieFileOutput))!
captureSession?.addOutput(movieFileOutput)

self.captureSession?.commitConfiguration()
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self as? AVCaptureMetadataOutputObjectsDelegate, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
videoPreviewLayer?.frame = previewLayer.layer.bounds
previewLayer.layer.addSublayer(videoPreviewLayer!)
captureSession?.startRunning()
self.btnCapture.isUserInteractionEnabled = true
catch let error
print(error.localizedDescription)




override func viewWillDisappear(_ animated: Bool)
super.viewWillDisappear(animated)
if let captureSession = self.captureSession
if captureSession.isRunning
captureSession.stopRunning()
self.captureSession = nil
self.btnCapture.isUserInteractionEnabled = false





Extension for AVCaptureFileOutputRecordingDelegate



extension MediaCaptureViewCotroller: AVCaptureFileOutputRecordingDelegate 
@objc func longPress(_ sender: UILongPressGestureRecognizer)
var device : AVCaptureDevice!
let videoDeviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)
let devices = videoDeviceDiscoverySession.devices
device = devices[0]
if sender.state == .began
print("Started...")
self.hideControls()
let videoPreviewLayerOrientation = videoPreviewLayer?.connection?.videoOrientation
if !movieFileOutput.isRecording
print("Recording...")
if UIDevice.current.isMultitaskingSupported
self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)

let movieFileOutputConnection = movieFileOutput.connection(with: .video)
movieFileOutputConnection?.videoOrientation = videoPreviewLayerOrientation!

let availableVideoCodecTypes = movieFileOutput.availableVideoCodecTypes

if #available(iOS 11.0, *)
if availableVideoCodecTypes.contains(.hevc)
movieFileOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: movieFileOutputConnection!)

else
movieFileOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecH264], for: movieFileOutputConnection!)

if ((device as AnyObject).hasMediaType(AVMediaType.video))
if (device.hasTorch)
self.captureSession?.beginConfiguration()
do
if (device.hasTorch)
catch
print("Device tourch Flash Error ");

self.captureSession?.commitConfiguration()


let outputFileName = NSUUID().uuidString
let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(("outputFileName" as NSString).appendingPathExtension("mp4")!)
print("RecordingStart PAth", outputFilePath)
self.cleanup(path: outputFilePath)
movieFileOutput.startRecording(to: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)

else if sender.state == .ended
print("Ended...")
if movieFileOutput.isRecording
print("Stopped")
movieFileOutput.stopRecording()
if ((device as AnyObject).hasMediaType(AVMediaType.video))
if (device.hasTorch)
self.captureSession?.beginConfiguration()
do
if (device.hasTorch)
try device.lockForConfiguration()
device.torchMode = .off
device.unlockForConfiguration()

catch
print("Device tourch Flash Error ");

self.captureSession?.commitConfiguration()


self.showControls()

else

func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?)
print(outputFileURL.absoluteString)
do
let data = try Data(contentsOf: outputFileURL)
print("Recorded File size", data.count)
//FIXME:- Navigate to create post screen
catch
print("error in decoding file", error.localizedDescription)

self.showControls()

func cleanup(path: String)
if FileManager.default.fileExists(atPath: path)
do
try FileManager.default.removeItem(atPath: path)
catch
print("Could not remove file at url: (path)")


if let currentBackgroundRecordingID = backgroundRecordingID
backgroundRecordingID = UIBackgroundTaskIdentifier.invalid
if currentBackgroundRecordingID != UIBackgroundTaskIdentifier.invalid
UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID)














share|improve this question


























    0















    I'm facing problem while recording the video.



    The flow is like :-



    1. I'll launch my camera screen.

    2. will record a video then will move to create post screen.

    3. This flow works fine for first time. But when I came back to camera from create post screen, and again try to record, It suddenly stops the recording as soon as i start and throws an error " there is no such file".

    Any help would be appreciated.
    Thanks.



    var captureSession: AVCaptureSession?
    var capturePhotoOutput: AVCapturePhotoOutput?
    var videoPreviewLayer: AVCaptureVideoPreviewLayer?
    var userSelectedFlashMode: AVCaptureDevice.FlashMode = .off

    override func viewDidAppear(_ animated: Bool)
    super.viewDidAppear(animated)
    captureSession = AVCaptureSession()
    captureSession?.beginConfiguration()
    let microphone = AVCaptureDevice.default(for: AVMediaType.audio)
    do
    let micInput = try AVCaptureDeviceInput(device: microphone!)
    if (captureSession?.canAddInput(micInput))!
    captureSession?.addInput(micInput)

    catch
    print("SRL Error setting device audio input.")

    guard let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back) else
    fatalError("No video device found")

    do
    let input = try AVCaptureDeviceInput(device: captureDevice)
    captureSession?.addInput(input)
    capturePhotoOutput = AVCapturePhotoOutput()
    capturePhotoOutput?.isHighResolutionCaptureEnabled = true
    captureSession?.addOutput(capturePhotoOutput!)
    captureSession?.sessionPreset = .high
    movieFileOutput.maxRecordedDuration = CMTimeMake(value: Int64(59), timescale: 1)
    if (captureSession?.canAddOutput(movieFileOutput))!
    captureSession?.addOutput(movieFileOutput)

    self.captureSession?.commitConfiguration()
    let captureMetadataOutput = AVCaptureMetadataOutput()
    captureSession?.addOutput(captureMetadataOutput)
    captureMetadataOutput.setMetadataObjectsDelegate(self as? AVCaptureMetadataOutputObjectsDelegate, queue: DispatchQueue.main)
    captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
    videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
    videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    videoPreviewLayer?.frame = previewLayer.layer.bounds
    previewLayer.layer.addSublayer(videoPreviewLayer!)
    captureSession?.startRunning()
    self.btnCapture.isUserInteractionEnabled = true
    catch let error
    print(error.localizedDescription)




    override func viewWillDisappear(_ animated: Bool)
    super.viewWillDisappear(animated)
    if let captureSession = self.captureSession
    if captureSession.isRunning
    captureSession.stopRunning()
    self.captureSession = nil
    self.btnCapture.isUserInteractionEnabled = false





    Extension for AVCaptureFileOutputRecordingDelegate



    extension MediaCaptureViewCotroller: AVCaptureFileOutputRecordingDelegate 
    @objc func longPress(_ sender: UILongPressGestureRecognizer)
    var device : AVCaptureDevice!
    let videoDeviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)
    let devices = videoDeviceDiscoverySession.devices
    device = devices[0]
    if sender.state == .began
    print("Started...")
    self.hideControls()
    let videoPreviewLayerOrientation = videoPreviewLayer?.connection?.videoOrientation
    if !movieFileOutput.isRecording
    print("Recording...")
    if UIDevice.current.isMultitaskingSupported
    self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)

    let movieFileOutputConnection = movieFileOutput.connection(with: .video)
    movieFileOutputConnection?.videoOrientation = videoPreviewLayerOrientation!

    let availableVideoCodecTypes = movieFileOutput.availableVideoCodecTypes

    if #available(iOS 11.0, *)
    if availableVideoCodecTypes.contains(.hevc)
    movieFileOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: movieFileOutputConnection!)

    else
    movieFileOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecH264], for: movieFileOutputConnection!)

    if ((device as AnyObject).hasMediaType(AVMediaType.video))
    if (device.hasTorch)
    self.captureSession?.beginConfiguration()
    do
    if (device.hasTorch)
    catch
    print("Device tourch Flash Error ");

    self.captureSession?.commitConfiguration()


    let outputFileName = NSUUID().uuidString
    let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(("outputFileName" as NSString).appendingPathExtension("mp4")!)
    print("RecordingStart PAth", outputFilePath)
    self.cleanup(path: outputFilePath)
    movieFileOutput.startRecording(to: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)

    else if sender.state == .ended
    print("Ended...")
    if movieFileOutput.isRecording
    print("Stopped")
    movieFileOutput.stopRecording()
    if ((device as AnyObject).hasMediaType(AVMediaType.video))
    if (device.hasTorch)
    self.captureSession?.beginConfiguration()
    do
    if (device.hasTorch)
    try device.lockForConfiguration()
    device.torchMode = .off
    device.unlockForConfiguration()

    catch
    print("Device tourch Flash Error ");

    self.captureSession?.commitConfiguration()


    self.showControls()

    else

    func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?)
    print(outputFileURL.absoluteString)
    do
    let data = try Data(contentsOf: outputFileURL)
    print("Recorded File size", data.count)
    //FIXME:- Navigate to create post screen
    catch
    print("error in decoding file", error.localizedDescription)

    self.showControls()

    func cleanup(path: String)
    if FileManager.default.fileExists(atPath: path)
    do
    try FileManager.default.removeItem(atPath: path)
    catch
    print("Could not remove file at url: (path)")


    if let currentBackgroundRecordingID = backgroundRecordingID
    backgroundRecordingID = UIBackgroundTaskIdentifier.invalid
    if currentBackgroundRecordingID != UIBackgroundTaskIdentifier.invalid
    UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID)














    share|improve this question
























      0












      0








      0








      I'm facing problem while recording the video.



      The flow is like :-



      1. I'll launch my camera screen.

      2. will record a video then will move to create post screen.

      3. This flow works fine for first time. But when I came back to camera from create post screen, and again try to record, It suddenly stops the recording as soon as i start and throws an error " there is no such file".

      Any help would be appreciated.
      Thanks.



      var captureSession: AVCaptureSession?
      var capturePhotoOutput: AVCapturePhotoOutput?
      var videoPreviewLayer: AVCaptureVideoPreviewLayer?
      var userSelectedFlashMode: AVCaptureDevice.FlashMode = .off

      override func viewDidAppear(_ animated: Bool)
      super.viewDidAppear(animated)
      captureSession = AVCaptureSession()
      captureSession?.beginConfiguration()
      let microphone = AVCaptureDevice.default(for: AVMediaType.audio)
      do
      let micInput = try AVCaptureDeviceInput(device: microphone!)
      if (captureSession?.canAddInput(micInput))!
      captureSession?.addInput(micInput)

      catch
      print("SRL Error setting device audio input.")

      guard let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back) else
      fatalError("No video device found")

      do
      let input = try AVCaptureDeviceInput(device: captureDevice)
      captureSession?.addInput(input)
      capturePhotoOutput = AVCapturePhotoOutput()
      capturePhotoOutput?.isHighResolutionCaptureEnabled = true
      captureSession?.addOutput(capturePhotoOutput!)
      captureSession?.sessionPreset = .high
      movieFileOutput.maxRecordedDuration = CMTimeMake(value: Int64(59), timescale: 1)
      if (captureSession?.canAddOutput(movieFileOutput))!
      captureSession?.addOutput(movieFileOutput)

      self.captureSession?.commitConfiguration()
      let captureMetadataOutput = AVCaptureMetadataOutput()
      captureSession?.addOutput(captureMetadataOutput)
      captureMetadataOutput.setMetadataObjectsDelegate(self as? AVCaptureMetadataOutputObjectsDelegate, queue: DispatchQueue.main)
      captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
      videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
      videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
      videoPreviewLayer?.frame = previewLayer.layer.bounds
      previewLayer.layer.addSublayer(videoPreviewLayer!)
      captureSession?.startRunning()
      self.btnCapture.isUserInteractionEnabled = true
      catch let error
      print(error.localizedDescription)




      override func viewWillDisappear(_ animated: Bool)
      super.viewWillDisappear(animated)
      if let captureSession = self.captureSession
      if captureSession.isRunning
      captureSession.stopRunning()
      self.captureSession = nil
      self.btnCapture.isUserInteractionEnabled = false





      Extension for AVCaptureFileOutputRecordingDelegate



      extension MediaCaptureViewCotroller: AVCaptureFileOutputRecordingDelegate 
      @objc func longPress(_ sender: UILongPressGestureRecognizer)
      var device : AVCaptureDevice!
      let videoDeviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)
      let devices = videoDeviceDiscoverySession.devices
      device = devices[0]
      if sender.state == .began
      print("Started...")
      self.hideControls()
      let videoPreviewLayerOrientation = videoPreviewLayer?.connection?.videoOrientation
      if !movieFileOutput.isRecording
      print("Recording...")
      if UIDevice.current.isMultitaskingSupported
      self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)

      let movieFileOutputConnection = movieFileOutput.connection(with: .video)
      movieFileOutputConnection?.videoOrientation = videoPreviewLayerOrientation!

      let availableVideoCodecTypes = movieFileOutput.availableVideoCodecTypes

      if #available(iOS 11.0, *)
      if availableVideoCodecTypes.contains(.hevc)
      movieFileOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: movieFileOutputConnection!)

      else
      movieFileOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecH264], for: movieFileOutputConnection!)

      if ((device as AnyObject).hasMediaType(AVMediaType.video))
      if (device.hasTorch)
      self.captureSession?.beginConfiguration()
      do
      if (device.hasTorch)
      catch
      print("Device tourch Flash Error ");

      self.captureSession?.commitConfiguration()


      let outputFileName = NSUUID().uuidString
      let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(("outputFileName" as NSString).appendingPathExtension("mp4")!)
      print("RecordingStart PAth", outputFilePath)
      self.cleanup(path: outputFilePath)
      movieFileOutput.startRecording(to: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)

      else if sender.state == .ended
      print("Ended...")
      if movieFileOutput.isRecording
      print("Stopped")
      movieFileOutput.stopRecording()
      if ((device as AnyObject).hasMediaType(AVMediaType.video))
      if (device.hasTorch)
      self.captureSession?.beginConfiguration()
      do
      if (device.hasTorch)
      try device.lockForConfiguration()
      device.torchMode = .off
      device.unlockForConfiguration()

      catch
      print("Device tourch Flash Error ");

      self.captureSession?.commitConfiguration()


      self.showControls()

      else

      func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?)
      print(outputFileURL.absoluteString)
      do
      let data = try Data(contentsOf: outputFileURL)
      print("Recorded File size", data.count)
      //FIXME:- Navigate to create post screen
      catch
      print("error in decoding file", error.localizedDescription)

      self.showControls()

      func cleanup(path: String)
      if FileManager.default.fileExists(atPath: path)
      do
      try FileManager.default.removeItem(atPath: path)
      catch
      print("Could not remove file at url: (path)")


      if let currentBackgroundRecordingID = backgroundRecordingID
      backgroundRecordingID = UIBackgroundTaskIdentifier.invalid
      if currentBackgroundRecordingID != UIBackgroundTaskIdentifier.invalid
      UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID)














      share|improve this question














      I'm facing problem while recording the video.



      The flow is like :-



      1. I'll launch my camera screen.

      2. will record a video then will move to create post screen.

      3. This flow works fine for first time. But when I came back to camera from create post screen, and again try to record, It suddenly stops the recording as soon as i start and throws an error " there is no such file".

      Any help would be appreciated.
      Thanks.



      var captureSession: AVCaptureSession?
      var capturePhotoOutput: AVCapturePhotoOutput?
      var videoPreviewLayer: AVCaptureVideoPreviewLayer?
      var userSelectedFlashMode: AVCaptureDevice.FlashMode = .off

      override func viewDidAppear(_ animated: Bool)
      super.viewDidAppear(animated)
      captureSession = AVCaptureSession()
      captureSession?.beginConfiguration()
      let microphone = AVCaptureDevice.default(for: AVMediaType.audio)
      do
      let micInput = try AVCaptureDeviceInput(device: microphone!)
      if (captureSession?.canAddInput(micInput))!
      captureSession?.addInput(micInput)

      catch
      print("SRL Error setting device audio input.")

      guard let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back) else
      fatalError("No video device found")

      do
      let input = try AVCaptureDeviceInput(device: captureDevice)
      captureSession?.addInput(input)
      capturePhotoOutput = AVCapturePhotoOutput()
      capturePhotoOutput?.isHighResolutionCaptureEnabled = true
      captureSession?.addOutput(capturePhotoOutput!)
      captureSession?.sessionPreset = .high
      movieFileOutput.maxRecordedDuration = CMTimeMake(value: Int64(59), timescale: 1)
      if (captureSession?.canAddOutput(movieFileOutput))!
      captureSession?.addOutput(movieFileOutput)

      self.captureSession?.commitConfiguration()
      let captureMetadataOutput = AVCaptureMetadataOutput()
      captureSession?.addOutput(captureMetadataOutput)
      captureMetadataOutput.setMetadataObjectsDelegate(self as? AVCaptureMetadataOutputObjectsDelegate, queue: DispatchQueue.main)
      captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
      videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
      videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
      videoPreviewLayer?.frame = previewLayer.layer.bounds
      previewLayer.layer.addSublayer(videoPreviewLayer!)
      captureSession?.startRunning()
      self.btnCapture.isUserInteractionEnabled = true
      catch let error
      print(error.localizedDescription)




      override func viewWillDisappear(_ animated: Bool)
      super.viewWillDisappear(animated)
      if let captureSession = self.captureSession
      if captureSession.isRunning
      captureSession.stopRunning()
      self.captureSession = nil
      self.btnCapture.isUserInteractionEnabled = false





      Extension for AVCaptureFileOutputRecordingDelegate



      extension MediaCaptureViewCotroller: AVCaptureFileOutputRecordingDelegate 
      @objc func longPress(_ sender: UILongPressGestureRecognizer)
      var device : AVCaptureDevice!
      let videoDeviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .unspecified)
      let devices = videoDeviceDiscoverySession.devices
      device = devices[0]
      if sender.state == .began
      print("Started...")
      self.hideControls()
      let videoPreviewLayerOrientation = videoPreviewLayer?.connection?.videoOrientation
      if !movieFileOutput.isRecording
      print("Recording...")
      if UIDevice.current.isMultitaskingSupported
      self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)

      let movieFileOutputConnection = movieFileOutput.connection(with: .video)
      movieFileOutputConnection?.videoOrientation = videoPreviewLayerOrientation!

      let availableVideoCodecTypes = movieFileOutput.availableVideoCodecTypes

      if #available(iOS 11.0, *)
      if availableVideoCodecTypes.contains(.hevc)
      movieFileOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecType.hevc], for: movieFileOutputConnection!)

      else
      movieFileOutput.setOutputSettings([AVVideoCodecKey: AVVideoCodecH264], for: movieFileOutputConnection!)

      if ((device as AnyObject).hasMediaType(AVMediaType.video))
      if (device.hasTorch)
      self.captureSession?.beginConfiguration()
      do
      if (device.hasTorch)
      catch
      print("Device tourch Flash Error ");

      self.captureSession?.commitConfiguration()


      let outputFileName = NSUUID().uuidString
      let outputFilePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(("outputFileName" as NSString).appendingPathExtension("mp4")!)
      print("RecordingStart PAth", outputFilePath)
      self.cleanup(path: outputFilePath)
      movieFileOutput.startRecording(to: URL(fileURLWithPath: outputFilePath), recordingDelegate: self)

      else if sender.state == .ended
      print("Ended...")
      if movieFileOutput.isRecording
      print("Stopped")
      movieFileOutput.stopRecording()
      if ((device as AnyObject).hasMediaType(AVMediaType.video))
      if (device.hasTorch)
      self.captureSession?.beginConfiguration()
      do
      if (device.hasTorch)
      try device.lockForConfiguration()
      device.torchMode = .off
      device.unlockForConfiguration()

      catch
      print("Device tourch Flash Error ");

      self.captureSession?.commitConfiguration()


      self.showControls()

      else

      func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?)
      print(outputFileURL.absoluteString)
      do
      let data = try Data(contentsOf: outputFileURL)
      print("Recorded File size", data.count)
      //FIXME:- Navigate to create post screen
      catch
      print("error in decoding file", error.localizedDescription)

      self.showControls()

      func cleanup(path: String)
      if FileManager.default.fileExists(atPath: path)
      do
      try FileManager.default.removeItem(atPath: path)
      catch
      print("Could not remove file at url: (path)")


      if let currentBackgroundRecordingID = backgroundRecordingID
      backgroundRecordingID = UIBackgroundTaskIdentifier.invalid
      if currentBackgroundRecordingID != UIBackgroundTaskIdentifier.invalid
      UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID)











      swift cocoa-touch avfoundation ios10 ios12






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 11:15









      Harshal YanpallewarHarshal Yanpallewar

      972410




      972410






















          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55062089%2frecording-a-video-stops-fileoutput-output-avcapturefileoutput-didfinishreco%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55062089%2frecording-a-video-stops-fileoutput-output-avcapturefileoutput-didfinishreco%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

          Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

          2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived