iOS扫描二维码方法

来源:互联网 发布:虚拟漫游软件 编辑:程序博客网 时间:2024/06/06 01:13


- (void)viewDidLoad {

    [superviewDidLoad];

//    self.hidesBottomBarWhenPushed=YES;

    

    [selfsetupDevice];//扫描二维码地方法

}

- (void)setupDevice

{

    //获取摄像设备

    AVCaptureDevice *device = [AVCaptureDevicedefaultDeviceWithMediaType:AVMediaTypeVideo];

    //创建输入流

    AVCaptureDeviceInput *input = [AVCaptureDeviceInputdeviceInputWithDevice:device error:nil];

    //创建输出流

    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutputalloc]init];

    //设置代理刷新

    [output setMetadataObjectsDelegate:selfqueue:dispatch_get_main_queue()];

    

    //初始化链接

    session = [[AVCaptureSessionalloc]init];

    //高质量采集率

    [session setSessionPreset:AVCaptureSessionPresetHigh];

    

    [session addInput:input];

    [session addOutput:output];

    //设置扫码支持的编码格式(如下设置条形码和二维码兼容

    

    [output setMetadataObjectTypes:[NSArrayarrayWithObjects:AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code, nil]];

    

    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayerlayerWithSession:session];

    layer.videoGravity =AVLayerVideoGravityResizeAspectFill;

    layer.frame = self.view.layer.bounds;

    [self.view.layerinsertSublayer:layer atIndex:0];

    

    //添加扫描框

    CGFloat viewWidth =self.view.frame.size.width;

    CGFloat viewHeight =self.view.frame.size.height;

    

   UIView *boxView = [[UIViewalloc]initWithFrame:CGRectMake(viewWidth/2 - 100, viewHeight/2 - 100, 200, 200)];

    boxView.backgroundColor = [UIColorclearColor];

    boxView.layer.borderColor = [UIColorgreenColor].CGColor;

    boxView.layer.borderWidth = 1.0f;

    [self.viewaddSubview:boxView];

    

    //设置扫描区域

   CGFloat x = boxView.frame.origin.y/viewHeight;

   CGFloat y = boxView.frame.origin.x/viewWidth;

   CGFloat width = 200/viewHeight;

   CGFloat height = 200/viewWidth;

    [outputsetRectOfInterest:CGRectMake(x, y, width, height)];

}


//扫描代理方法

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection

{

   if (metadataObjects.count > 0) {

        [session stopRunning];

       AVMetadataMachineReadableCodeObject *metadataobject = [metadataObjectsobjectAtIndex:0];

       NSLog(@"%@", metadataobject.stringValue);

        url = [NSStringstringWithFormat:@"%@", metadataobject.stringValue];

     

        [selfplayVideo];

    }

}


- (void)playVideo

{

   if (url) {

       NSURL *movieUrl = [NSURLURLWithString:url];

        VideoPlayerViewController *videoController = [[VideoPlayerViewControlleralloc]initWithNibName:@"VideoPlayerViewController"bundle:nil];

        videoController.url = movieUrl;

        [self.navigationControllerpushViewController:videoController animated:YES];

    }

}


1 0
原创粉丝点击