Some basic usage methods of camera in iOS development are Shared

  • 2020-05-12 06:15:29
  • OfStack

In some applications, we need to use the camera of iOS device to take photos and videos. And select the pictures or videos we need from the album.
For the iOS camera and photo album applications, you can use the UIImagePickerController class to do the control.

The UIImagePickerController class provides you with the ability to take photos, as well as the ability to browse pictures and videos.

Check whether the hardware has a camera installed or allows you to operate the album

#pragma mark - 摄像头和相册相关的公共类
// Determine if the device has a camera
- (BOOL) isCameraAvailable{
return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
// Whether the front camera is available
- (BOOL) isFrontCameraAvailable{
return [UIImagePickerControllerisCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
// Whether the rear camera is available
- (BOOL) isRearCameraAvailable{
return [UIImagePickerControllerisCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];

Call the camera

- (BOOL) hasMultipleCameras {
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
if (devices != nil && [devices count] > 1) return YES;
return NO;
} - (AVCaptureDevice *)cameraWithPosition : (AVCaptureDevicePosition) position
NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *device in devices )
if ( device.position == position )
return device; return nil ;
} - (void) swapFrontAndBackCameras {
//check for available cameras!
if (![self hasMultipleCameras]) return; //assumes session is running
NSArray *inputs = self.captureSession.inputs; //should only be one value!
for ( AVCaptureDeviceInput *captureDeviceInput in inputs ) {
AVCaptureDevice *device = captureDeviceInput.device ;
if ( [device hasMediaType:AVMediaTypeVideo ] ) {
AVCaptureDevicePosition position = device.position ;
AVCaptureDevice *newCamera = nil ;
AVCaptureDeviceInput *newInput = nil ; if (position == AVCaptureDevicePositionFront)
newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront]; [self initializeCaptureDevice:newCamera];
newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil]; // beginConfiguration ensures that pending changes are not applied immediately
[self.captureSession beginConfiguration ]; [self.captureSession removeInput:captureDeviceInput]; //remove current
[self.captureSession addInput:newInput]; //add new // Changes take effect once the outermost commitConfiguration is invoked.
[self.captureSession commitConfiguration];
break ;

The code above USES front and rear cameras!

Related articles: