Switch front/back camera with AVCaptureSession

durazno picture durazno · Aug 7, 2015 · Viewed 14.7k times · Source

I'm following the only answer this has on SO -

Switch cameras with avcapturesession

However cameraWithPosition does not seem to work. Deprecated?

//Get new input
    AVCaptureDevice *newCamera = nil;
    if(((AVCaptureDeviceInput*)currentCameraInput).device.position == AVCaptureDevicePositionBack)
    {
        newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
    }
    else
    {
        newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
    }

Answer

0yeoj picture 0yeoj · Aug 7, 2015

What you need to do is reconfigure your AVCaptureSession

Here is what i'm using:

// note that `AVCaptureSession * session`
//
if(session)
{
    [session beginConfiguration];

    AVCaptureInput *currentCameraInput = [session.inputs objectAtIndex:0];

    [session removeInput:currentCameraInput];

    AVCaptureDevice *newCamera = nil;

    if(((AVCaptureDeviceInput*)currentCameraInput).device.position == AVCaptureDevicePositionBack)
    {
        newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
    }
    else
    {
        newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
    }

    NSError *err = nil;

    AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];

    if(!newVideoInput || err)
    {
        NSLog(@"Error creating capture device input: %@", err.localizedDescription);
    }
    else
    {
        [session addInput:newVideoInput];
    }

    [session commitConfiguration];
}

// make sure you have this method in your class
//
- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position
{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

    for (AVCaptureDevice *device in devices)
    {
        if ([device position] == position)
            return device;
    }
    return nil;
}