#import "ViewController.h"
//记得添加AVFoundation框架,另外,二维码扫描需要硬件摄像头的支持,所以只能真机运行。模拟器获取不到信息
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property(nonatomic,strong)AVCaptureDevice *captureDevice;//代表了硬件设备
@property(nonatomic,strong)AVCaptureSession *captureSession;//这玩意完全就是一个中介.链接硬件设备跟输入输出
@property(nonatomic,strong)AVCaptureVideoPreviewLayer *videoPreviewLayer;//这玩意就是看到的那个扫描的框框啊
@property(nonatomic,strong)AVCaptureMetadataOutput *output;//信息输出
@property(nonatomic,strong)AVCaptureDeviceInput *input;//信息输入
@end
@implementation ViewController
{
UIView *_viewPreview;//这东西是添加在主视图里呈现videoPreviewLayer
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//创建一个承载扫描的view
_viewPreview=[[UIView alloc]initWithFrame:CGRectMake(200, 20, 100, 100)];
[self.view addSubview:_viewPreview];
NSError *error=nil;
_captureDevice=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
_input=[AVCaptureDeviceInput deviceInputWithDevice:_captureDevice error:&error];
if (!_input) {
NSLog(@"error=========%@",[error localizedDescription]);
}else{
_captureSession=[[AVCaptureSession alloc]init];
//设置会话的输入设备
[_captureSession addInput:_input];
//对应输出
_output=[[AVCaptureMetadataOutput alloc]init];
[_captureSession addOutput:_output];
//创建一个队列.其实这个队列可以选择性创建。详情自己去百度
dispatch_queue_t dispatchQueue;
dispatchQueue = dispatch_queue_create("myQueue", NULL);
[_output setMetadataObjectsDelegate:self queue:dispatchQueue];
//这东西是编码格式
[_output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]];
//将捕获的数据流展现出来
_videoPreviewLayer=[[AVCaptureVideoPreviewLayer alloc]initWithSession:_captureSession];
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
[_viewPreview.layer addSublayer:_videoPreviewLayer];
[_captureSession startRunning];
}
}
//这个代理函数是扫描完了获取到信息以后调用的,通常在这里结束
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
if (metadataObjects !=nil && [metadataObjects count]>0) {
AVMetadataMachineReadableCodeObject *metadataObj=[metadataObjects objectAtIndex:0];
if ([[metadataObj type]isEqualToString:AVMetadataObjectTypeQRCode]) {
//获得扫描数据,并结束扫描
[self performSelectorOnMainThread:@selector(stopReading:) withObject:metadataObj.stringValue waitUntilDone:NO];
}
}
}
-(void)stopReading:(NSString *)str{
[_captureSession stopRunning];
NSLog(@"str=======%@",str);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end