iOS二維碼掃描

weixin_34185560發表於2016-01-14

先上圖(詳細的都在keynote畫出來了>_<


325120-8de4105f532368cd.jpg
二維碼掃描工作原理.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; 
      }
}

相關文章