IOS Toggle AVFoundation Camera

▼魔方 西西 提交于 2019-12-06 13:24:52

If your captureSession's sessionPreset is not compatible with the camera you're switching to it will fail the canAddInput test. I always reset to AVCaptureSessionPresetHigh before toggling cameras then try to switch it to whatever preset I have preferred. Here's the code I use:

- (void)toggleCamera {
  AVCaptureDevicePosition newPosition = self.currentCameraPossition == AVCaptureDevicePositionBack ? AVCaptureDevicePositionFront : AVCaptureDevicePositionBack;
  AVCaptureDevice *device = [self videoDeviceWithPosition:newPosition];
  AVCaptureDeviceInput *deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];

  [_captureSession beginConfiguration];
  [_captureSession removeInput:self.deviceInput];
  [_captureSession setSessionPreset:AVCaptureSessionPresetHigh]; //Always reset preset before testing canAddInput because preset will cause it to return NO

  if ([_captureSession canAddInput:deviceInput]) {
    [_captureSession addInput:deviceInput];
    self.deviceInput = deviceInput;
    self.currentCameraPossition = newPosition;
  } else {
      [_captureSession addInput:self.deviceInput];
  }

  if ([device supportsAVCaptureSessionPreset:self.sessionPreset]) {
    [_captureSession setSessionPreset:self.sessionPreset];
  }

  if ([device lockForConfiguration:nil]) {
    [device setSubjectAreaChangeMonitoringEnabled:YES];
    [device unlockForConfiguration];
  }

  [_captureSession commitConfiguration];
} 

I have seen issues with toggle code not working if it is not run on the main thread. Can you try wrapping your code with the following block:

dispatch_async(dispatch_get_main_queue(), ^{
   // Your camera toggle code goes here
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!