0

I've set up my app to take a photo using AVCaptureDevice.

The code below works perfectly however when I change both the ".back" to ".front" I get a crash:

'NSRangeException', reason: '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'

let session = AVCaptureDeviceDiscoverySession.init(deviceTypes: [.builtInDualCamera], mediaType: AVMediaTypeVideo, position: .back)
    if let device = session?.devices[0] {

        if device.position == AVCaptureDevicePosition.back {

            do {

                let input = try AVCaptureDeviceInput(device: device )
                if captureSession.canAddInput(input){
                    captureSession.addInput(input)
                    stillImageOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]

                    if captureSession.canAddOutput(stillImageOutput) {
                        captureSession.addOutput(stillImageOutput)
                        captureSession.startRunning()

                        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                        previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.portrait
                        cameraView.layer.addSublayer(previewLayer)

                        previewLayer.bounds = cameraView.frame
                        previewLayer.position = CGPoint(x: cameraView.frame.width / 2, y:cameraView.frame.height / 2)
                    }

                }

            }                catch {


            }
        }
    }
Alex Ingram
  • 434
  • 4
  • 17
  • Possible duplicate of [How to get front camera, back camera and audio with AVCaptureDeviceDiscoverySession](https://stackoverflow.com/questions/39894630/how-to-get-front-camera-back-camera-and-audio-with-avcapturedevicediscoverysess) – Brian Ogden Jun 18 '17 at 17:05
  • I am voting close, you will find your answer here: https://stackoverflow.com/a/39895097/1258525 – Brian Ogden Jun 18 '17 at 17:06
  • For your understanding,there are no devices in the `devices` array so this line of your code fails: let device = session?.devices[0] You are attempting to access the first item in an empty array. The front camera is not a `builtInDualCamera` type so the combination of deviceType .builtInDualCamera and position .front yields zero results from the discovery session – Brian Ogden Jun 18 '17 at 17:09
  • @BrianOgden I am getting a crash on that line, is it required? – Alex Ingram Jun 18 '17 at 22:34

0 Answers0