iOS二维码扫描

先上图(详细的都在keynote画出来了>_<


iOS二维码扫描_第1张图片
二维码扫描工作原理.jpg

图永远都是最清晰明了的。下边说说注意事项:

     //如果没获得权限
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
    [AlertView alertWithTitle:nil message:@"亲,请先到系统“隐私”中打开相机权限哦!" buttonTitle:@"知道啦!" confrimBlock:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    return;
}
   _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

   _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];

   _output = [[AVCaptureMetadataOutput alloc]init];
   [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])  {
         [_session addInput:self.input];
    }

    if ([_session canAddOutput:self.output])  {
           [_session addOutput:self.output];
     }
      // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];

    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity =AVLayerVideoGravityResize;
    _preview.frame =self.view.layer.bounds;
    [self.view.layer insertSublayer:_preview atIndex:0];

    [_session startRunning];

  //设置扫描输出口的视图捕捉范围
    [_output setRectOfInterest:CGRectMake(cropRect.origin.y / screenHeight,
                                      cropRect.origin.x / screenWidth,
                                      cropRect.size.height / screenHeight,
                                      cropRect.size.width / screenWidth)];
        
 最后实现代理方法:
   #pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
        NSString *stringValue;
       if ([metadataObjects count] >0){
           //停止扫描
            [_session stopRunning];
            AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects safeObjectAtIndex:0];
            stringValue = metadataObject.stringValue;
       }else{
            //扫码失败
            [self.session startRunning];
            return; 
      }
}

你可能感兴趣的:(iOS二维码扫描)