Search code examples
iosswiftavcapturesession

AVFoundation- Camera Switches Once, And Only Once


I found this great thread here on StackOverflow and used it to write my switchCamera function in Swift.

I've got it working so that when I press my button, the camera switches to the Back camera. However, it does not switch back to the Front camera once I press it again. What did I do wrong in my code that doesn't allow the camera to be switched again?

One extra note: When I translated the code mentioned in the the thread above, I was unable to return nil in my cameraWithPosition(). Not sure if that's what is causing my issue.

My Code:

@IBAction func switchCamera(sender: UIButton) {
    let currentCameraInput: AVCaptureInput = session.inputs[0] as! AVCaptureInput
    session.removeInput(currentCameraInput)

    let newCamera: AVCaptureDevice?
    if(captureDevice!.position == AVCaptureDevicePosition.Back){
        println("Setting new camera with Front")
        newCamera = self.cameraWithPosition(AVCaptureDevicePosition.Front)
    } else {
        println("Setting new camera with Back")
        newCamera = self.cameraWithPosition(AVCaptureDevicePosition.Back)
    }

    let newVideoInput = AVCaptureDeviceInput(device: newCamera!, error: nil)
    if(newVideoInput != nil) {
        session.addInput(newVideoInput)
    } else {
        println("Error creating capture device input")
    }

    session.commitConfiguration()

}

func cameraWithPosition(position: AVCaptureDevicePosition) -> AVCaptureDevice {
    let devices = AVCaptureDevice.devices()
    for device in devices {
            if(device.position == position){
                return device as! AVCaptureDevice
            }
    }
    return AVCaptureDevice()
}

Solution

  • 5 Minutes after I post the question and I figure it out, lol.

    My issue was that I did not set my initial captureDevice equal to the newly created AVCaptureDevice which I called newCamera.

    So to fix that I simply did this at the end of switchCamera()...

    captureDevice! = newCamera!