Check which camera is currently in use in iOS Appl

2019-08-19 04:17发布

问题:

I'm writing an app which has a custom made view for taking photos with the Camera, similar to Apple's AVCam. In it, I want to make a button disappear and re-appear for the flash icon every time the camera is switched. IE When using the front camera, the flash button shouldn't be there and when using the back it should!

My code for this at the moment is:

  AVCaptureDevicePosition position = [[videoInput device] position];

    if (position == AVCaptureDevicePositionBack) {
  self.flashButton.hidden == YES;
}

But it comes up with an error on the videoInput and I'm not sure why... Any documentation you could direct me to or ideas for changes in my code would be much appreciated!

EDIT

Just basically specifically why does it come up with the error of 'use of undeclared identifier' with this code:

AVCaptureDevicePosition position = [[videoInput device] position];

回答1:

The below code might help you :

AVCaptureDeviceInput *newVideoInput;
AVCaptureDevicePosition currentCameraPosition = [[videoInput device] position];

if (currentCameraPosition == AVCaptureDevicePositionBack)
{
    currentCameraPosition = AVCaptureDevicePositionFront;
}
else
{
    currentCameraPosition = AVCaptureDevicePositionBack;
}

AVCaptureDevice *backFacingCamera = nil;
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices) 
{
    if ([device position] == currentCameraPosition)
    {
        backFacingCamera = device;
    }
}
newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:backFacingCamera error:&error];


回答2:

I was looking for a solution for similar issue and came up with this and it might work for you (only tested in iOS8 and written in Swift):

var captureDevice : AVCaptureDevice?

...

var currentDevice:String = captureDevice?.localizedName as String!

if currentDevice.rangeOfString("Back Camera") != nil {
   //hide flash icon
} else if currentDevice.rangeOfString("Front Camera") != nil {
   //show flash icon
}

This code assumes that you already have setup the camera properly

Note: This may not be the best way because if Apple decides to change the localizedName it will break. And, I know this question is ancient but it might help someone else who stumbles on it