导入#import <AVFoundation/AVFoundation.h>
遵守AVCaptureMetadataOutputObjectsDelegate代理
定义属性:
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
//懒加载device。默认调用后置摄像头
-(AVCaptureDevice *)device{
NSArray *Devices = [AVCaptureDevicedevicesWithMediaType:AVMediaTypeVideo];
for (AVCaptureDevice *Devicein Devices)
{
//设置为前置摄像头,也可为后置
if ([Deviceposition] == AVCaptureDevicePositionFront )
{
return Device;
}
}
return nil;
}
ViewDidLoad中设置相机:
// Input
_input = [AVCaptureDeviceInputdeviceInputWithDevice:self.deviceerror:nil];
// Output
_output = [[AVCaptureMetadataOutputalloc]init];
[_outputsetMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];
// Session
_session = [[AVCaptureSessionalloc]init];
[_sessionsetSessionPreset:AVCaptureSessionPresetHigh];
if ([_sessioncanAddInput:self.input])
{
[_session addInput:self.input];
}
if ([_sessioncanAddOutput:self.output])
{
[_session addOutput:self.output];
}
// 条码类型 AVMetadataObjectTypeQRCode
// iOS8 下需要使用新的 API
NSMutableArray *array = [[NSMutableArrayalloc] initWithObjects:AVMetadataObjectTypeQRCode,AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeCode128Code, AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeAztecCode, nil];
if ([[[UIDevicecurrentDevice] systemVersion]floatValue] >= 8.0){
[array addObject:AVMetadataObjectTypeInterleaved2of5Code];
[array addObject:AVMetadataObjectTypeITF14Code];
[array addObject:AVMetadataObjectTypeDataMatrixCode];
}
//必须加上判断系统是否支持,否则会出错
if ([self.output.availableMetadataObjectTypescontainsObject:array]) {
_output.metadataObjectTypes = array;
}
// Preview
_preview =[AVCaptureVideoPreviewLayerlayerWithSession:self.session];
_preview.videoGravity =AVLayerVideoGravityResizeAspectFill;
_preview.frame =CGRectMake(0,0, [UIScreenmainScreen].bounds.size.width , [UIScreenmainScreen].bounds.size.height);/// 220 *220
//_preview.frame = CGRectMake([UIScreen mainScreen].bounds.size.width/2-110, [UIScreen mainScreen].bounds.size.height/2-110, 220, 220);
[self.view.layerinsertSublayer:self.previewatIndex:0];
// Start
[_sessionstartRunning];
#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
NSString *stringValue = @"";
if ([metadataObjects count] > 0)
{
AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjectsobjectAtIndex:0];
stringValue = metadataObject.stringValue;
}
// 发起网络请求
// if (![NSString MyStringIsNULL:stringValue]) {
// [_session stopRunning];
// [self netWithStr:stringValue];
// }
}