In my Swift project, I have a camera feature. The camera is used to video recording with a basic start / stop - record button and a preview of the video. Everything works except one thing. I have a UIbutton
which will switch between the front and the back camera of the phone. The the target function works as expected when the AVCaptureSession
is not running. But after it is started, the button will stop the AVCaptureSession
instead of just changing the camera.
Here's my function (the one triggered by the switch-button):
@objc func switchCameraClicked() {
let session: AVCaptureSession = captureSession
session.beginConfiguration()
if (captureDevice?.position == .front) {
captureDevice = AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInWideAngleCamera, for: AVMediaType.video, position: .back)
} else {
captureDevice = AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInWideAngleCamera, for: AVMediaType.video, position: .front)
}
if let inputs = session.inputs as? [AVCaptureDeviceInput] {
for input in inputs {
if input.device.deviceType != AVCaptureDevice.DeviceType.builtInMicrophone {
session.removeInput(input)
} else {
print("Keep the microphone!")
}
}
}
do {
try session.addInput(AVCaptureDeviceInput(device: captureDevice!))
} catch {
print(error)
}
session.commitConfiguration()
captureSession = session
}
EDIT:
The AVCaptureSession
stops at session.removeInput(input)
and triggers the func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?)
delegate method.
Let me hear your suggestions.
Thanks!