0

I'm getting an error saying:

cannot instantiate a AVCaptureDevice directly

When I'm trying to set the camera to the front camera. My code looks like this:

        let inputDevice:AVCaptureDevice = setCameraPosition()

        var error:NSError?
        let deviceInput:AVCaptureDeviceInput = AVCaptureDeviceInput.deviceInputWithDevice(inputDevice, error: &error) as AVCaptureDeviceInput

func setCameraPosition()->AVCaptureDevice{
    let devices = AVCaptureDevice.devices()
    var captureDevice = AVCaptureDevice()

    // Loop through all the capture devices on this phone
    for device in devices {
        // Make sure this particular device supports video
        if (device.hasMediaType(AVMediaTypeVideo)) {
            // Finally check the position and confirm we've got the back camera
            if(device.position == AVCaptureDevicePosition.Front) {
                captureDevice = device as AVCaptureDevice
            }
        }
    }
    return captureDevice
}

I am able to use the back camera by using this line of code:

let inputDevice:AVCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

and I am not able to figure out where it goes wrong.

Any suggestions on how to proceed would be appreciated.

martin
  • 1,894
  • 4
  • 37
  • 69
  • Which line is the error on? – NobodyNada Feb 06 '15 at 21:26
  • If the top 3 lines of the code you posted are outside of a method, it's not going to work because you're using inputDevice to define deviceInput and that's not allowed outside of a method. – Lyndsey Scott Feb 06 '15 at 21:28
  • @NobodyNada It doesn't say, it's an NSInvalidArgumentException. but it has to be in the function. – martin Feb 06 '15 at 21:28
  • @frank21 Set an exception breakpoint and tell us which line it's on. – NobodyNada Feb 06 '15 at 21:29
  • @LyndseyScott They are not outside a method, as I said, the code works with the last line I posted. It's just the way I'm trying to instantiate the front camera which is the problem. – martin Feb 06 '15 at 21:30
  • Like the error states, you can't instantiate your AVCaptureDevice directly. This answer should help explain: http://stackoverflow.com/a/27644082/2274694 – Lyndsey Scott Feb 06 '15 at 21:39
  • @LyndseyScott Thank you, I thought I had done that correctly, looked at it again and realized I hadn't done it correctly. – martin Feb 06 '15 at 21:45

0 Answers0