Reputation: 833
I am using AV Foundation and I have setup a button that I want to toggle between the front facing and rear facing camera when tapped.
If I run the app, and tap the button, the console tells me that I have successfully changed the device to the front facing camera, but the the screen still shows me what the rear camera is seeing.
I need to update the screen so that it really is showing what the front camera sees and really does capture what the front camera sees.
Here is my IBAction code that is hooked up to my toggle button:
-(IBAction)toggleCamera {
_inputDevice = [self frontCamera];
}
And here is the method implementation that is powering "frontCamera":
- (AVCaptureDevice *)frontCamera {
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) {
if ([device position] == AVCaptureDevicePositionFront) {
NSLog(@"Device position during frontCamera method: %d", [device position]);
return device;
}
}
return nil;
}
Upvotes: 0
Views: 253
Reputation: 3751
You need to do more than just setting the input device. Do you have an AVCaptureSession set up? If so, each time you swap the camera, you would need to (1) reconfigure the session, (2) remove the current input, (3) add the new input and (4) commit the session configuration:
// Define a flag in your header file to keep track of the current camera input
BOOL isUsingFrontFacingCamera;
-(IBAction)toggleCamera
{
// determine the mode to switch to
AVCaptureDevicePosition desiredPosition;
if (isUsingFrontFacingCamera)
{
desiredPosition = AVCaptureDevicePositionBack;
}
else
desiredPosition = AVCaptureDevicePositionFront;
}
for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType: AVMediaTypeVideo])
{
if ([d position] == desiredPosition)
{
// configure the session
[session beginConfiguration];
// find and clear all the existing inputs
for (AVCaptureInput *oldInput in [session inputs])
{
[session removeInput:oldInput];
}
// add the new input to session
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil];
[session addInput:input];
// commit the configuration
[session commitConfiguration];
break;
}
}
// update the flag to reflect the current mode
isUsingFrontFacingCamera = !isUsingFrontFacingCamera;
}
Answer adapted from this post
Upvotes: 1