1. 程式人生 > >ios開發拍照功能之裝置前後攝像頭切換

ios開發拍照功能之裝置前後攝像頭切換

#import <AVFoundation/AVFoundation.h>

#pragma mark - 攝像頭和相簿相關的公共類

// 判斷裝置是否有攝像頭

- (BOOL) isCameraAvailable{

return [UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];

}

// 前面的攝像頭是否可用

- (BOOL) isFrontCameraAvailable{

return [UIImagePickerControllerisCameraDeviceAvailable

:UIImagePickerControllerCameraDeviceFront];

}

// 後面的攝像頭是否可用

- (BOOL) isRearCameraAvailable{

return [UIImagePickerControllerisCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];

}

-  (BOOL) hasMultipleCameras {

NSArray *devices = [AVCaptureDevicedevicesWithMediaType:AVMediaTypeVideo];

if (devices !=

nil && [devices count] > 1) returnYES;

returnNO;

}

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position

{

NSArray *devices = [AVCaptureDevicedevicesWithMediaType:AVMediaTypeVideo];

for (AVCaptureDevice *device in devices )

if ( device.position == position )

return device;

returnnil ;

}

- (void)swapFrontAndBackCameras {

//check for available cameras!

if (![selfhasMultipleCameras]) 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 = [selfcameraWithPosition:AVCaptureDevicePositionBack];

else

                newCamera = [selfcameraWithPosition:AVCaptureDevicePositionFront];

            [self initializeCaptureDevice:newCamera];

            newInput = [AVCaptureDeviceInputdeviceInputWithDevice: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 ;

        }

    }

}