Hassan
Hassan

Reputation: 183

Scanning barcode with AVCaptureMetadataOutput and AVFoundation

I am using AVFoundation and AVCaptureMetadataOutput to scan a QR barcode in iOS7, I present a view controller which allows the user to scan a barcode. It is working fine, ie. a barcode is being scanned and I can output the barcode string to console.

But it keeps scanning over and over again, see screen shot. What I want it to do is scan the barcode just the once and then dismissViewController.

Here is my code for the delegate method:

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
CGRect highlightViewRect = CGRectZero;

AVMetadataMachineReadableCodeObject *barCodeObject;
NSString *detectionString = nil;
NSArray *barCodeTypes = @[AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code,
        AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code,
        AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode];

for (AVMetadataObject *metadata in metadataObjects) {
    for (NSString *type in barCodeTypes) {
        if ([metadata.type isEqualToString:type])
        {
            barCodeObject = (AVMetadataMachineReadableCodeObject *)[self.preview transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata];
            highlightViewRect = barCodeObject.bounds;
            detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
            break;
        }
    }

    if (detectionString != nil)
    {
        NSLog(@"Barcode: %@", detectionString);

        break;
    }
    else
        NSLog(@"None");
}

self.highlightView.frame = highlightViewRect;

}

enter image description here

Upvotes: 2

Views: 6508

Answers (2)

S.S.D
S.S.D

Reputation: 1676

You need to stop the captureSesson using: captureSession.stopRunning() once the barcode is scanned, otherwise it will keep scanning the code even if videoPreviewLayer is stopped.

Upvotes: 0

user3106702
user3106702

Reputation: 21

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    ....
    self.highlightView.frame = highlightViewRect;
    [_session stopRunning]; //<---I add this and it worked for me.
}

Here is a good link that might help.

Upvotes: 2

Related Questions