Reject a barcode

Motivation

Once you enable one or more symbologies, the Scandit Barcode Scanner will scan all codes belonging to the enabled symbologies. When a barcode is scanned, then the phone will be vibrating/beeping, and the recognized code might be visually highlighted depending on the GUI style used. However, sometimes, you might want to apply your own logic (i.e. validate the code via a regular expression) before accepting a code. With the Scandit Barcode Scanner this is very easy to achieve and in this guide, we will show you how to do that.

Code Rejection

In order to be able to accept only a subset of the codes, it is necessary to enable code rejection.

Objective-C:

- (void)setupScanner {
// Enable the relevant symbologies.
...
// Enable code rejection
scanSettings.codeRejectionEnabled = YES;
}

Swift:

func setupScanner() {
let scanSettings = SBSScanSettings.default()
// Enable the relevant symbologies.
...
// Enable code rejection
scanSettings.codeRejectionEnabled = true
}

Once this is done, you can use SBSScanSession's rejectCode: method to reject individual codes. Here you can find an example where we iterate through all the recognized codes and possibly reject a few of them after calling shouldRejectCode: which is the method containing the app logic used to decide whether to reject the code or not.

Objective-C:

- (void)barcodePicker:(SBSBarcodePicker *)picker didScan:(SBSScanSession *)session {
for (SBSCode *code in session.newlyRecognizedCodes) {
if ([self shouldRejectCode:code]) {
[session rejectCode:code];
}
}
...
}

Swift:

func barcodePicker(_ picker: SBSBarcodePicker, didScan session: SBSScanSession) {
for code in session.newlyRecognizedCodes {
if shouldReject(code) {
session.reject(code)
}
}
...
}

Please note, that rejectCode:, must be called from the session queue. If you need to switch to a different queue, in order to decide if you should reject the code or not, you should block the session queue. The most common way to achieve this is via dispatch sync. Here is an example.

Objective-C:

- (void)barcodePicker:(SBSBarcodePicker *)picker didScan:(SBSScanSession *)session {
for (SBSCode *code in session.newlyRecognizedCodes) {
__block BOOL shouldReject = NO;
dispatch_sync(self.anotherQueue, ^{
shouldReject = [self shouldRejectCode:code];
});
if (shouldReject) {
[session rejectCode:code];
}
}
...
}

Swift:

func barcodePicker(_ picker: SBSBarcodePicker, didScan session: SBSScanSession) {
for code in session.newlyRecognizedCodes {
var shouldReject = false
anotherQueue.sync {
shouldReject = shouldReject(code)
}
if shouldReject {
session.reject(code)
}
}
...
}