cannot change the camera position to front in AVCaptureDevice

Viewed 128

I'm Swift learner and making a camera app and I want to add adjusting focus and exposure function to my front camera. I've already done adding that function to the back camera. In the code below, I set my default camera position as back, and depending on the user's tapped location, the camera starts to adjust camera focus and exposure. (I didn't add that function in here but basically, it passes user tapped location to setFocus function, and like I wrote before, it works for back camera.) The function, flipCamera, changes camera location (i.e. from back to front camera), and I can use my front camera. However, when I check the print statement in setFocus, it logs

<AVCaptureFigVideoDevice: 0x14 [Back Camera][com.apple.avfoundation.avcapturedevice.built-in_video:0]>

even when I use my front camera. Also, I cannot adjust camera focus and exposure when I use the front camera. I thought in the flipCamera function I changed the camera position, but I guess I'm doing wrong. Could anyone point out what I'm doing wrong?

private var currentPosition: AVCaptureDevice.Position = .back
private var captureDevice = AVCaptureDevice.default(for: .video)
@IBOutlet private weak var lfView: MTHKView!

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    rtmpStream.attachCamera(DeviceUtil.device(withPosition: .back)) { error in
        logger.warn(error.description)
    }
    lfView?.attachStream(rtmpStream)
}

func setFocus(focusMode: AVCaptureDevice.FocusMode, exposureMode: AVCaptureDevice.ExposureMode, atPoint devicePoint: CGPoint, shouldMonitorSujectAreaChange: Bool) {
    
    guard let captureDevice = captureDevice else { return }
    
    print("capture device \(captureDevice)")
    // more code in here...

}
    
@IBAction func flipCamera(_ sender: Any) {
    if currentPosition == .back {
        print("to front")
        currentPosition = .front
        rtmpStream.attachCamera(DeviceUtil.device(withPosition: currentPosition)) { error in
            logger.warn(error.description)
            
            // cannot use auto focus when using front camera...
        }
    } else {
        
        print("to back")
        currentPosition = .back
        rtmpStream.attachCamera(DeviceUtil.device(withPosition: currentPosition)) { error in
            logger.warn(error.description)
        }
    }
}
0 Answers
Related