iOS 系统扫码、扫一扫

2021-07-09  本文已影响0人  乔帮主123

@property (nonatomic, assign) BOOL isReading;

@property (nonatomic, strong) AVCaptureSession *captureSession;

@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;

- (BOOL)startReading {

    _isReading = YES;

    NSError*error;

    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];

    if(!input) {

        NSLog(@"%@", [errorlocalizedDescription]);

        returnNO;

    }

    _captureSession = [[AVCaptureSession alloc] init];

    // Set the input device on the capture session.

    [_captureSession addInput:input];

    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];

    [_captureSessionaddOutput:captureMetadataOutput];

    // Create a new serial dispatch queue.

    dispatch_queue_tdispatchQueue;

    dispatchQueue =dispatch_queue_create("myQueue",NULL);

    [captureMetadataOutputsetMetadataObjectsDelegate:selfqueue:dispatchQueue];

    [captureMetadataOutputsetMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode, nil]];

    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];

    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];

    [_videoPreviewLayer setFrame:self.view.layer.bounds];

    [self.view.layer addSublayer:_videoPreviewLayer];

    [_captureSession startRunning];

    return YES;

}

-(void)stopReading{

    [_captureSession stopRunning];

    _captureSession = nil;

    [_videoPreviewLayer removeFromSuperlayer];

}

-(void)captureOutput:(AVCaptureOutput*)captureOutputdidOutputMetadataObjects:(NSArray*)metadataObjects

      fromConnection:(AVCaptureConnection*)connection

{

    if(!_isReading)return;

    if(metadataObjects !=nil&& [metadataObjectscount] >0) {

        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];

        NSLog(@"----%@",metadataObj);

        // 提醒

        [LBXScanWrapper systemVibrate];

        [LBXScanWrapper systemSound];

//        [self stopReading];

    }

}

上一篇 下一篇

猜你喜欢

热点阅读