- (void)viewDidLoad {
[super viewDidLoad];
// self.hidesBottomBarWhenPushed=YES;
[self setupDevice];//扫描二维码地方法
}- (void)setupDevice
{
//获取摄像设备
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 setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, nil]];
AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
layer.frame = self.view.layer.bounds;
[self.view.layer insertSublayer:layer atIndex:0];
//添加扫描框
CGFloat viewWidth = self.view.frame.size.width;
CGFloat viewHeight = self.view.frame.size.height;
UIView *boxView = [[UIView alloc]initWithFrame:CGRectMake(viewWidth/2 - 100, viewHeight/2 - 100, 200, 200)];
boxView.backgroundColor = [UIColor clearColor];
boxView.layer.borderColor = [UIColor greenColor].CGColor;
boxView.layer.borderWidth = 1.0f;
[self.view addSubview:boxView];
//设置扫描区域
CGFloat x = boxView.frame.origin.y/viewHeight;
CGFloat y = boxView.frame.origin.x/viewWidth;
CGFloat width = 200/viewHeight;
CGFloat height = 200/viewWidth;
[output setRectOfInterest:CGRectMake(x, y, width, height)];
}
//扫描代理方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
if (metadataObjects.count > 0) {
[session stopRunning];
AVMetadataMachineReadableCodeObject *metadataobject = [metadataObjects objectAtIndex:0];
NSLog(@"%@", metadataobject.stringValue);
url = [NSString stringWithFormat:@"%@", metadataobject.stringValue];
[self playVideo];
}
}
- (void)playVideo
{
if (url) {
NSURL *movieUrl = [NSURL URLWithString:url];
VideoPlayerViewController *videoController = [[VideoPlayerViewController alloc]initWithNibName:@"VideoPlayerViewController" bundle:nil];
videoController.url = movieUrl;
[self.navigationController pushViewController:videoController animated:YES];
}
}