Search code examples
ioszxingscanning

Stop Continuous scanning in ZxingObjC


I am using Zxing to scan the data matrix codes. I imported the zxing from github . When the app starts , the camera is scanning the code repeatedly as long as the camera is placed on a barcode.I want to stop the scanning once the barcode is decoded and I want to perform a task and then again start scanning. I stopped the scanning but unable to start it. Here is what I have done to stop the scanning.

Here is my ViewController.m

- (void)captureResult:(ZXCapture *)capture result:(ZXResult *)result {
if (!result) return;

// We got a result. Display information about the result onscreen.
NSString *formatString = [self barcodeFormatToString:result.barcodeFormat];
NSString *display = [NSString stringWithFormat:@"Scanned!\n\nFormat: %@\n\nContents:\n%@",  formatString, result.text];

//here i called the stop method 
 [self.capture stop];

//i want to start scanning again ,so i created this method
 [self afterScan];
}

Now once the barcode is decoded the camera is stopped. Now i want to implement this method

 -(void) afterScan{

 // UIAlertVIew " code is decoded "
  // store in database

 // again start scanning
      [self.capture start];

  }

The problem is the camera is not starting again.

The start and stop methods in the ZXing are as follows:

- (void)start {
if (self.hardStop) {
return;
}

if (self.delegate || self.luminanceLayer || self.binaryLayer) {
[self output];
}

if (!self.session.running) {
static int i = 0;
if (++i == -2) {
  abort();
}

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  [self.session startRunning];
});
}
 self.running = YES;
}

 - (void)stop {
  if (!self.running) {
 return;
 }

 if (self.session.running) {
 [self.layer removeFromSuperlayer];

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  [self.session stopRunning];
    //[self.session startRunning];
  });
 }

 self.running = NO;


 }

Could you please help me in solving this issue.

Thanks in advance.


Solution

  • When I did it, I used a BOOL property.

    So put one in your view controller like this:

    @property (nonatomic, assign) BOOL hasScannedResult;
    

    Then you need an if() condition check to ensure your method doesn't get called repeatedly.

    - (void)captureResult:(ZXCapture *)capture result:(ZXResult *)result {
    
        if(self.hasScannedResult == NO)
        {
    
            self.hasScannedResult = YES;
    
            // do something with result
        }
    }
    

    Now when you want to scan again, reset the BOOL flag:

    -(void)startScan
    {
        // reset BOOL flag to enable scanning
        self.hasScannedResult = NO;
    
        // open the scanner
    }