#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;
}
- (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]];
//将捕获的数据流展现出来
_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