I'm currently developing a custom camera feature in my Swift app where users can choose from available cameras on their phones, such as front, back, dual wide, etc. The problem is that when the user switches to a different camera, it takes a considerable amount of time to load the new camera, causing the app to lag. Is there any way to optimize this process?
Function for displaying available cameras:
func showListOfAvailableCameras(_ delegate: IVSCustomBroadcast, devices: [AvailableCameras]) {
let alert = UIAlertController(
title: "Available Cameras",
message: nil,
preferredStyle: .actionSheet
)
for device in devices {
let action = UIAlertAction(
title: device.friendlyName,
style: .default
) { _ in
self.broadcastSession.didCameraChoose(chosen: device.device)
}
alert.addAction(action)
}
alert.addAction(UIAlertAction(title: "general.alert.cancel".value, style: .cancel))
alert.popoverPresentationController?.sourceView = self.view
alert.popoverPresentationController?.sourceRect = self.view.bounds
present(alert, animated: true)
}
Function that gets executed when a camera is selected:
func didCameraChoose(chosen device: AVCaptureDevice) {
let currentVideoDevice = self.videoDeviceInput.device
sessionQueue.async {
do {
let videoDeviceInput = try AVCaptureDeviceInput(device: device)
self.session.beginConfiguration()
self.session.removeInput(self.videoDeviceInput)
if self.session.canAddInput(videoDeviceInput) {
NotificationCenter.default.removeObserver(
self,
name: .AVCaptureDeviceSubjectAreaDidChange,
object: currentVideoDevice
)
NotificationCenter.default.addObserver(
self,
selector: #selector(self.subjectAreaDidChanged(_:)),
name: .AVCaptureDeviceSubjectAreaDidChange,
object: videoDeviceInput.device
)
self.session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
self.session.removeOutput(self.videoOutput)
self.addVideoOutput()
} else {
self.session.addInput(self.videoDeviceInput)
}
self.session.commitConfiguration()
} catch {
self.delegate?.didCameraErrorOccured(self, error: "Error occurred while creating video device input: \(error)")
}
}
}
I would greatly appreciate any insights or suggestions on how to optimize the camera switching process. Thank you in advance for your kind assistance!