您的位置:首页 > 移动开发 > IOS开发

IOS 使用AVFoundation 扫描条形码、二维码等

2015-04-05 17:49 501 查看
在IOS7之前,我们一般都是通过ZXing或者ZBar来进行二维码、条形码的扫描识别。但在IOS7之后,我们可以直接调用AVFoundation来进行码的扫描识别,一下是代码(当然要导入AVFoundation.framework)

- (void)setupCamera
{
// Device
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

// Input
self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];

// Output
self.output = [[AVCaptureMetadataOutput alloc]init];
[self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

// Session
self.session = [[AVCaptureSession alloc]init];//会话
[self.session setSessionPreset:AVCaptureSessionPresetHigh];
if ([self.session canAddInput:self.input])
{
[self.session addInput:self.input];
}
if ([self.session canAddOutput:self.output])
{
[self.session addOutput:self.output];
}

// 条码类型
self.output.metadataObjectTypes =@[AVMetadataObjectTypeCode39Code];//条形码

// Preview
self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
self.preview.videoGravity =AVLayerVideoGravityResizeAspectFill;
self.preview.frame =CGRectMake(0,200,self.view.frame.size.width, 100);//扫描区域

//    //CALayer--扫描区域红线
//    CALayer *line = [CALayer layer];
//    [line setFrame:CGRectMake(0, self.preview.frame.size.height/2, self.preview.frame.size.width, 1)];
//    [line setBackgroundColor:[UIColor redColor].CGColor];
//
//    [self.preview addSublayer:line];
[self.view.layer addSublayer:self.preview];

// Start
[self.session startRunning];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
// 会频繁的扫描,调用代理方法
// 1. 如果扫描完成,停止会话
[self.session stopRunning];
// 2. 删除预览图层
[self.preview removeFromSuperlayer];

//    NSLog(@"%@", metadataObjects);
// 3. 设置界面显示扫描结果

if (metadataObjects.count > 0) {
AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
// 提示:如果需要对url或者名片等信息进行扫描,可以在此进行扩展!
//        _captureLabel.text = obj.stringValue;
_label.text = obj.stringValue;
NSLog(@"%@", obj.stringValue);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: