ios – Swift AVFoundation function to flip camera doesn’t work


I have a function below to toggle between the front and back camera. This function below works but I have to click a button twice that calls this function for the camera to actually flip. I tried debugging the problem but can’t figure out why the flip only works on the second try. Im not quite sure why the session is behaving like this.

    func flipCamera() {
        guard let currentVideoInput = session.inputs.first as? AVCaptureDeviceInput else {
            return
        }

        session.beginConfiguration()
        session.removeInput(currentVideoInput)

        let newCameraPosition: AVCaptureDevice.Position = (currentCameraPosition == .back) ? .front : .back
        guard let newCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: newCameraPosition) else {
            session.commitConfiguration()
            return
        }

        do {
            let newVideoInput = try AVCaptureDeviceInput(device: newCamera)

            if session.canAddInput(newVideoInput) {
                session.addInput(newVideoInput)
                currentCameraPosition = newCameraPosition
            } else {
                session.addInput(currentVideoInput) // Re-add the old input if new input fails
            }
        } catch {
            print("Error creating new camera input: \(error)")
            session.addInput(currentVideoInput) // Re-add the old input in case of error
        }

        session.commitConfiguration()
    }

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img