在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);
}
}