声明
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@protocol PassNumber
-(void)PassNumberdata:(id)_data;
@end
@interface DZC_Scan_Bar : UIViewController<AVCaptureMetadataOutputObjectsDelegate>
{
AVCaptureSession * session;//输入输出的中间桥梁
}
@property (weak, nonatomic) IBOutlet UIView *Scan_View;
@property (strong,nonatomic)id<PassNumber>delegate;
@end
实现
“`
import “DZC_Scan_Bar.h”
@interface DZC_Scan_Bar ()
@end
@implementation DZC_Scan_Bar
(void)viewDidLoad {
[super viewDidLoad];
//获取摄像设备
AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//创建输入流
AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
//创建输出流
AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
//设置代理 在主线程里刷新
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];//初始化链接对象
session = [[AVCaptureSession alloc]init];
//高质量采集率
[session setSessionPreset:AVCaptureSessionPresetHigh];[session addInput:input];
[session addOutput:output];
//设置扫码支持的编码格式(如下设置条形码和二维码兼容)
output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
layer.frame=CGRectMake(10,SCREENHEIGHT/2-90, SCREENWIDTH-20, 180);//self.Scan_View.layer.bounds;
[self.view.layer insertSublayer:layer atIndex:0];
//开始捕获
[session startRunning];
}(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)captureOutput:(AVCaptureOutput )captureOutput didOutputMetadataObjects:(NSArray )metadataObjects fromConnection:(AVCaptureConnection *)connection{
if (metadataObjects.count>0) {
[session stopRunning];
AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
//输出扫描字符串
DLog(@”%@”,metadataObject.stringValue);
[self.navigationController popViewControllerAnimated:YES];
[self.delegate PassNumberdata:metadataObject.stringValue];}
}
/*
pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end“`