Skip to main content

Barcode Scanner | React Native Barcode Scanner

Storage#

Scanbot Barcode Scanner SDK uses the internal and secure storage locations for the optional barcode images by default.

  • On Android all files will be stored in the internal files directory of your application. No permissions are required for your app to read or write files in this directory.

  • On iOS all files will be stored in the Application Support folder of your application.

Customize Storage Location#

It is strongly recommended to use the default storage location. However, you can override the storage directory on initialization of the SDK Module. The initializeSdk method can take an optional parameter storageBaseDirectory to set a custom storage location.

const options = {  storageBaseDirectory: 'file:///some/custom/storage-dir/',  ...};
const result = await ScanbotBarcodeSdk.initializeSdk(options);

The value of the storageBaseDirectory must be a file URL ('file:///...) pointing to a valid platform-specific file system path. If this directory does not exist yet, the SDK Module will try to create it. To work with the file system we recommend the npm module react-native-fs

For the full demo code please check out our example app scanbot-barcode-scanner-sdk-example-react-native.

โš ๏ธ Note: When overriding the default storage location, make sure

  • you have implemented a suitable storage permissions request handling on Android
  • you fully understand the consequences regarding the accessibility (security) of the produced document files.

๐Ÿ‘‰ For more details about the storage locations on Android and iOS please also see:

Storage Cleanup#

There is no automatic file clean mechanism in this SDK Module, because only your App can decide when the perfect time is to remove the optional barcode image files produced by this SDK.

To avoid storage space issues caused by too many produced image files, it is strongly recommended to implement a suitable cleanup functionality based on the requirements of your app. This SDK Module provides the following helper method to keep the storage clean:

  • cleanup method to remove all generated barcode image files by this module.

Barcode and QR Code Scanning UI#

Barcode Scanner#

ScanbotBarcodeSdk.startBarcodeScanner(configuration: BarcodeScannerConfiguration): Promise<BarcodeResult> Opens a scanning UI for barcodes and QR codes.

alt

Returns#

The promise resolves to an object with the following properties:

interface BarcodeResult {  status: string; // 'OK' if the screen completed successfully, `'CANCELED'` if the user canceled the screen.  imageUri: string; // optional file URI to the saved image where the barcodes were found. Set only if `barcodeImageGenerationType` in the configuration is not "NONE".  barcodes: [  // An array of found barcodes, empty if no barcodes were found.    {      type: string; // the type of the found barcode, e.g. "QR_CODE"      text: string; // the raw text encoded in the barcode.      imagePath: string; // iOS-only: the path to the saved image crop containing the barcode.    }  ];}
Options:#

All settings are optional.

  • barcodeFormats is an optional array of barcode formats that acts as a detection filter. By default all supported formats will be detected.

  • acceptedDocumentFormats is an optional array of barcode document formats that acts as a document type filter. By default all supported document formats will be detected.

export interface BarcodeScannerConfiguration{    /**     * An optional array of barcode document formats that act as a detection filter.     * By default all supported document formats will be detected.     */    acceptedDocumentFormats?: BarcodeDocumentFormat[];    /**     * Allowed orientations for automatic interface rotations. *     */    allowedInterfaceOrientations?: UIInterfaceOrientationMask;    /**     * Background color of the detection overlay.     */    cameraOverlayColor?: string;    /**     * Whether the cancel button is hidden or not.     */    cancelButtonHidden?: boolean;    /**     * String being displayed on the cancel button.     */    cancelButtonTitle?: string;    /**     * Foreground color of the detection overlay.     */    finderLineColor?: string;    /**     * Width of finder frame border. Default is 2.     */    finderLineWidth?: number;    /**     * String being displayed as description.     */    finderTextHint?: string;    /**     * Foreground color of the description label.     */    finderTextHintColor?: string;    /**     * Aspect ratio of finder frame (width \ height), which is used to build actual finder frame.     * Default is 1 - it is a square frame, which is good for QR capturing.     */    finderAspectRatio?: FinderAspectRatio;    /**     * String being displayed on the flash button.     */    flashButtonTitle?: string;    /**     * Foreground color of the flash button when flash is off.     */    flashButtonInactiveColor?: string;    /**     * Whether the flash is toggled on or off.     */    flashEnabled?: boolean;    /**     * Optional minimum required text length of the detected barcode.     * The default is 0 (setting is turned off).     * NOTE: This feature works on ITF and MSI Plessey barcodes only.     */    minimumTextLength?: number,    /**     * Optional maximum required text length of the detected barcode.     * The default is 0 (setting is turned off).     * NOTE: This feature works on ITF and MSI Plessey barcodes only.     */    maximumTextLength?: number,    /**     * Optional minimum required quiet zone on the barcode.     * Measured in modules (the size of minimal bar on the barcode).     * The default is 10.     * NOTE: This feature works on ITF and MSI Plessey barcodes only.     */    minimum1DBarcodesQuietZone?: number    /**     * Whether scanner screen should make a sound on successful barcode or MRZ detection.     */    successBeepEnabled?: boolean;    /**     * Background color of the top bar.     */    topBarBackgroundColor?: string;    /**     * Foreground color of the cancel button.     */    topBarButtonsColor?: string;    /**     * Accepted barcode formats     */    barcodeFormats?: BarcodeFormat[];    /**     * Specifies the way of barcode images generation or disables this generation at all.     * Use, if you want to receive a full sized image with barcodes. Defaults to NONE.     */    barcodeImageGenerationType?: BarcodeImageGenerationType;    /**     * Controls whether buttons should use all capitals style, as defined by the Android Material Design. Defaults to TRUE.     * Android only.     */    useButtonsAllCaps?: boolean;    /**     * With this option, the scanner assumes that the barcode can be a GS1 barcode, and modify the behavior as needed.     * You can set it to 'false', if you don't want to see decoded FNC1 characters ("]C1" and ASCII char 29).     * The default is 'true'.     * NOTE: Currently works for CODE128 barcodes only!     */    enableGS1Decoding?: boolean;    /**     * The relative initial zoom level of the camera in the range [0,1], where 0 is zoomed out and 1 is zoomed in.     * The default value is 0.     */    cameraZoomFactor?: number;    /**     * The engine mode of the barcode recognizer. Defaults to NEXT_GEN.     * To use legacy recognizer, please specify LEGACY     */    engineMode?: EngineMode;    /**     * When set to `true`, the scanner assumes that the barcode can be a GS1 barcode.     * Turn it off, if you don't want to see decoded FNC1 characters ("]C1" and ASCII char 29).     * The default value is `true`.     * NOTE: Currently works for CODE128 barcodes only!     */    gs1DecodingEnabled?: boolean;    /**     * The checksum algorithms for MSI Plessey barcodes.     * The default value is [MSIPlesseyChecksumAlgorithm.Mod10].     */    msiPlesseyChecksumAlgorithm?: MSIPlesseyChecksumAlgorithm;    /**     * With this option enabled, the scanner removes checks digits for UPC, EAN and MSI Plessey codes.     * Has no effect if both single and double digit MSI Plessey checksums are enabled.     * The default is `false`     */    stripCheckDigits?: boolean;}
Force Close#

You can programmatically force the Barcode Scanner to close:

await ScanbotBarcodeSDK.closeBarcodeScanner();

Batch Barcode Scanner#

ScanbotBarcodeSdk.startBatchBarcodeScanner(configuration: BatchBarcodeScannerConfiguration): Promise<BatchBarcodeScannerResult> Opens a Scanning UI to scan multiple barcodes and QR-codes in a row.

Callbacks:#

successCallback : function(result)
  • result.status - 'OK' if a barcode was detected, 'CANCELED' if the user canceled the operation (tapped on the "cancel" button).
  • result.barcodes[] - Array of detected barcodes. If no barcodes were detected, the array will be empty or null.
  • result.barcodes[n].type - Format of detected barcode/QR code (e.g. CODE_128, EAN_13, QR_CODE, etc).
  • result.barcodes[n].text - Text value of detected and decoded barcode/QR code.
  • result.imageFileUri - Optional file URI of the captured camera image.
errorCallback : function(error)
  • error.status - 'ERROR' in all error cases.
  • error.message - Contains the error message as a string.

Options:#

All settings are optional.

barcodeFormats is an optional array of barcode formats that acts as a detection filter. By default all supported formats will be detected.

acceptedDocumentFormats is an optional array of barcode document formats that act as a detection filter. By default all supported document formats will be detected.

export interface BatchBarcodeScannerConfiguration{    /**     * An optional array of barcode document formats that act as a detection filter.     * By default all supported document formats will be detected.     */    acceptedDocumentFormats?: BarcodeDocumentFormat[];    /**     * Allowed orientations for automatic interface rotations. *     */    allowedInterfaceOrientations?: UIInterfaceOrientationMask;    /**     * String used for displaying amount of scanned barcodes. Use %d for number formatting symbol.     */    barcodesCountText?: string;    /**     * Text color of the barcodes count label.     */    barcodesCountTextColor?: string;    /**     * Background color of the detection overlay.     */    cameraOverlayColor?: string;    /**     * Whether the cancel button is hidden or not. (iOS Only)     */    cancelButtonHidden?: boolean;    /**     * The relative initial zoom level of the camera in the range [0,1], where 0 is zoomed out and 1 is zoomed in.     * The default value is 0.     */    cameraZoomFactor?: number;    /**     * String being displayed on the cancel button.     */    cancelButtonTitle?: string;    /**     * String being displayed on the clear button.     */    clearButtonTitle?: string;    /**     * String being displayed on the delete button.     */    deleteButtonTitle?: string;    /**     * Foreground color of the top bar buttons on the details screen.     */    detailsActionColor?: string;    /**     * Background color of the details screen.     */    detailsBackgroundColor?: string;    /**     * Text color in the details barcodes list. Also affects image background, separator and progress spinner.     */    detailsPrimaryColor?: string;    /**     * String used to show process of fetching mapped data for barcodes.     */    fetchingStateText?: string;    /**     * Aspect ratio of finder frame (width \ height), which is used to build actual finder frame.     * Default is 1 - it is a square frame, which is good for QR capturing.     */    finderAspectRatio?: FinderAspectRatio;    /**     * Foreground color of the detection overlay.     */    finderLineColor?: string;    /**     * Width of finder frame border. Default is 2.     */    finderLineWidth?: number;    /**     * String being displayed as description.     */    finderTextHint?: string;    /**     * Foreground color of the description label.     */    finderTextHintColor?: string;    /**     * Whether the flash is toggled on or off.     */    flashEnabled?: boolean;    /**     * String to show that no barcodes were scanned yet.     */    noBarcodesTitle?: string;    /**     * String being displayed on the submit button.     */    submitButtonTitle?: string;    /**     * Whether scanner screen should make a sound on successful barcode or MRZ detection.     */    successBeepEnabled?: boolean;    /**     * Background color of the top bar.     */    topBarBackgroundColor?: string;    /**     * Foreground color of the top bar buttons on the scanning screen.     */    topBarButtonsColor?: string;    /**     * Foreground color of the flash button when flash is off.     */    topBarButtonsInactiveColor?: string;    /**     * Accepted barcode formats     */    barcodeFormats?: BarcodeFormat[];    /**     * Controls whether buttons should use all capitals style, as defined by the Android Material Design. Defaults to TRUE.     * Android only.     */    useButtonsAllCaps?: boolean;    /**    * Optional minimum required text length of the detected barcode.    * The default is 0 (setting is turned off).    * NOTE: This feature works on ITF and MSI Plessey barcodes only.    */    minimumTextLength?: number;   /**    * Optional maximum required text length of the detected barcode.    * The default is 0 (setting is turned off).    * NOTE: This feature works on ITF and MSI Plessey barcodes only.    */    maximumTextLength?: number;   /**    * Optional minimum required quiet zone on the barcode.    * Measured in modules (the size of minimal bar on the barcode).    * The default is 10.     * NOTE: This feature works on ITF and MSI Plessey barcodes only.    */    minimum1DBarcodesQuietZone?: number;    /**    * With this option, the scanner assumes that the barcode can be a GS1 barcode, and modify the behavior as needed.    * You can set it to 'false', if you don't want to see decoded FNC1 characters ("]C1" and ASCII char 29).    * The default is 'true'.    * NOTE: Currently works for CODE128 barcodes only!    */    enableGS1Decoding?: boolean;
    /**     * The engine mode of the barcode recognizer. Defaults to NEXT_GEN.     * To use legacy recognizer, please specify LEGACY     */    engineMode?: EngineMode;
    /**     * When set to `true`, the scanner assumes that the barcode can be a GS1 barcode.     * Turn it off, if you don't want to see decoded FNC1 characters ("]C1" and ASCII char 29).     * The default value is `true`.     * NOTE: Currently works for CODE128 barcodes only!     */    gs1DecodingEnabled?: boolean;
    /**     * The checksum algorithms for MSI Plessey barcodes.     * The default value is [MSIPlesseyChecksumAlgorithm.Mod10].     */    msiPlesseyChecksumAlgorithm?: MSIPlesseyChecksumAlgorithm;
    /**     * With this option enabled, the scanner removes checks digits for UPC, EAN and MSI Plessey codes.     * Has no effect if both single and double digit MSI Plessey checksums are enabled.     * The default is `false`     */    stripCheckDigits?: boolean;}
Force Close#

You can programmatically force the Batch Barcode Scanner to close:

await ScanbotBarcodeSDK.closeBatchBarcodeScanner();

Enums#

UI Interface Orientation Mask#

export type UIInterfaceOrientationMask =    "PORTRAIT"    | "LANDSCAPE_LEFT"    | "LANDSCAPE_RIGHT"    | "PORTRAIT_UPSIDE_DOWN"    | "LANDSCAPE"    | "ALL"    | "ALL_BUT_UPSIDE_DOWN"    ;

Barcode Image Generation Type#

export type BarcodeImageGenerationType =    "NONE"    | "FROM_VIDEO_FRAME"    | "CAPTURED_IMAGE"    ;

Barcode Format#

export type BarcodeFormat =    "AZTEC" |    "CODABAR" |    "CODE_39" |    "CODE_93" |    "CODE_128" |    "DATA_MATRIX" |    "EAN_8" |    "EAN_13" |    "ITF" |    "PDF_417" |    "QR_CODE" |    "RSS_14" |    "RSS_EXPANDED" |    "UPC_A" |    "UPC_E" |    "UNKNOWN";

Barcode Document Format#

export type BarcodeDocumentFormat =    "AAMVA" |    "BOARDING_PASS" |    "DE_MEDICAL_PLAN" |    "DISABILITY_CERTIFICATE" |    "ID_CARD_PDF_417" |    "SEPA" |    "SWISS_QR" |    "VCARD";

Barcode Detection from Still Images#

ScanbotBarcodeSdk.detectBarcodesOnImage(args: DetectBarcodesOnImageArgs): Promise<BarcodeResult> This method provides the functionality of detecting barcodes from a still image, e.g. a JPG image from Photo Library or other source. The image must be passed as a file URI.

Arguments object:

interface DetectBarcodesOnImageArgs {  imageFileUri: string, // file URI to a local image in which to search for barcodes  barcodeFormats?: BarcodeFormat[], // Accepted Barcode Formats  acceptedDocumentFormats?: BarcodeDocumentFormat[], // Accepted Document Formats  minimumTextLength?: number, // Barcode minimum accepted length (ITF and MSI Plessey barcodes only).  maximumTextLength?: number, // Barcode maximum accepted length (ITF and MSI Plessey barcodes only).  minimum1DBarcodesQuietZone?: number // Barcode minimum quiet zone (ITF and MSI Plessey barcodes only).}

The returned object has the same type as the one returned by startBarcodeScanner.

Example:

try {  const result = await ScanbotBarcodeSdk.detectBarcodesOnImage({    imageFileUri: "file:///..."  });  if (result.status === "OK") {    // do something with result.barcodes  }} catch (e) {  // ...}

Native Components#

You can use native components to embed our Barcode Scanning functionalities directly into your React layouts, allowing you to customize the user interface and experience in great detail and precision.

Note: Native Components are bundled with react-native-scanbot-barcode-scanner-sdk starting from v3.0.1

Barcode Camera View#

The Barcode Camera View component (ScanbotBarcodeCameraView) exposes a configurable camera view that allows you to detect barcodes in real time.

Usage#

import {ScanbotBarcodeCameraView} from 'react-native-scanbot-barcode-scanner-sdk';

You can then include it in your layout as you would normally do with other React components:

render() {  return (    <>      <SafeAreaView>        <ScanbotBarcodeCameraView style={this.styles.cameraView}/>      </SafeAreaView>    </>  );}

Detecting Barcodes#

You can use the onBarcodeScannerResult property to handle the detection results.

render() {  return (    <>      <SafeAreaView>        <ScanbotBarcodeCameraView           style={{this.styles.cameraView}}          onBarcodeScannerResult={(result: ScanbotBarcodeCameraViewResult) => {              console.log(result);          }}          />      </SafeAreaView>    </>  );}

Result Object#

  • status -> OK or CANCELED
  • barcodes -> the array of barcodes that have been detected
    • text -> the barcode text
    • type -> the barcode type

Configuration#

You can customise the UI and Behavior of the Barcode Camera View by using the component configuration property. Every property is optional and it falls back to its default value when not specified.

  /**   * The finder view is a rectangular overlay view that clips the camera view,   * so that the detection will focus on just a specific area. You can specify   * the size and positioning, as well as other UI properties.   * Set this property to `true` if you want to use the Finder View, `false` otherwise (default: false)   */  shouldUseFinderView?: boolean;  /**   * The finder view rectangular overlay border width   */  finderLineWidth?: number;  /**   * The finder view rectangular overlay border color   */  finderLineColor?: string;  /**   * The overlay background color, around the finder view rectangle   */  finderBackgroundColor?: string;  /**   * The overlay background color opacity, around the finder view rectangle   */  finderBackgroundOpacity?: number;  /**   * The finder view rectangle aspect ratio   */  finderAspectRatio?: FinderAspectRatio;  /**   * The finder view minimum padding from the bounds of the screen   */  finderMinimumPadding?: number;  /**   * How many pixel units the finder view should be moved vertically by;   *    * Positive values -> (UP); Negative values -> (DOWN)   */  finderVerticalOffset?: number;  /**  * Whether the flash is toggled on or off.  */  flashEnabled?: boolean;  /**   * List of accepted Barcode Formats; any formats that are not included in this   * list will not be detected by the `BarcodeCameraView`. By default, the list   * includes all supported barcode types.   */  barcodeFormats?: BarcodeFormat[];  /**   * List of accepted Document Formats; any document formats that are not included   * in this list will be ignored by the `BarcodeCameraView`. By default, the list   * includes all supported document types.   */  acceptedDocumentFormats?: BarcodeDocumentFormat[];  /**   * The checksum algorithm for MSI Plessey barcodes.   * The default value is `Mod10'   */  msiPlesseyChecksumAlgorithm?: MSIPlesseyChecksumAlgorithm;  /**   * The engine mode of the barcode recognizer. Defaults to NEXT_GEN.   * To use legacy recognizer, please specify LEGACY   */  engineMode?: EngineMode;  /**   * The relative initial zoom level of the camera in the range [0,1], where 0 is zoomed out and 1 is zoomed in.   * The default value is 0.   */  cameraZoomFactor?: number;  /**   * When set to `true`, the scanner assumes that the barcode can be a GS1 barcode.   * Turn it off, if you don't want to see decoded FNC1 characters ("]C1" and ASCII char 29).   * The default value is `true`.   * NOTE: Currently works for CODE128 barcodes only.   */  gs1DecodingEnabled?: boolean;  /**   * Optional minimum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF and MSI Plessey barcodes only.   */  minimumTextLength?: number;  /**   * Optional maximum required text length of the detected barcode.   * The default is 0 (setting is turned off).   * NOTE: This feature works on ITF and MSI Plessey barcodes only.   */  maximumTextLength?: number;  /**   * With this option enabled, the scanner removes checks digits for UPC, EAN and MSI Plessey codes.   * Has no effect if both single and double digit MSI Plessey checksums are enabled.   * The default is `false`   */  stripCheckDigits?: boolean;

Example

<ScanbotBarcodeCameraView    configuration={{    shouldUseFinderView: true,    finderAspectRatio: {      width: 2,      height: 1    },    finderLineWidth: 2.0,    finderLineColor: '#ffffff',    finderBackgroundColor: '#000000',    finderBackgroundOpacity: 0.66,    finderMinimumPadding: 16,    finderVerticalOffset: -300,    barcodeFormats: ["CODE_128", "EAN_13"]  }}    onBarcodeScannerResult={(result: ScanbotBarcodeCameraViewResult) => {    console.log(result);  }}
  style={this.styles.cameraView} />

Cleanup#

ScanbotBarcodeSdk.cleanup(): Promise By calling ths function all optional barcode image files generated by the Scanbot Barcode Scanner SDK module will be deleted.

File Handling & Storage Concept#

The Scanbot Barcode SDK module works with file URIs. That means all input and output files (images, etc) are identified by a file URI. Please note that a file URI is not just a file path : "file:///some/file/path/.." vs. "/some/file/path/.."

Examples of valid file URIs:

  • On Android: file:///storage/emulated/0/Android/data/my.awesome.app/cache/sbsdk-temp/ce8de3c4-3c96-4ce1-b285-483d01e1dc9a.jpg

  • On iOS: file:///var/mobile/Containers/Data/Application/D2BF9FB2-1024-4418-99B2-3709AB2C171E/Documents/sbsdk-temp/05719BF8-63DB-4C8A-9A57-25B233AED33C.jpg

All output files generated by the Scanbot Barcode SDK module are temporary files. We recommend copying, moving or deleting the files you get from callbacks to an appropriate storage place.

There is no automatic file clean mechanism in the module, because only your App can decide when the perfect time is to remove a file.

To avoid storage space issues caused by temporary files please implement a suitable hook for the cleanup function in your App.

Building Production Apps#

iOS#

The Scanbot Barcode SDK iOS Framework (included in this React Native npm package) contains the most used architectures (arm64, armv7, x86_64, i386). You can thus run it on most iOS devices as well as on simulators during the development phase. To be able to submit a production build to the App Store or a test build for TestFlight you have to remove (strip away) the architectures x86_64 and i386 from the Scanbot Barcode Scanner SDK Framework. These architectures are only for simulators and not allowed to be submitted to App Store Connect.

To accomplish this, we provide a script strip-SBSDK-Framework.sh which is part of the ScanbotBarcodeScannerSDK.framework and can be easily integrated in the build process. This script removes the unnecessary architectures from the frameworks binary, code signs the framework and adds the crash symbols (dSYM) file to your app's archive. The final package size (IPA) of your app will then be significantly smaller than a debug version used during the development phase.

To add this script in your build process, you will need to open the Xcode workspace .xcworkspace and apply a few changes there:

  1. Go to TARGETS settings and open the tab Build Phases. Add a new Run Script Phase via "+" button.
  2. Adjust this Run Script Phase with the following script data:

Script code:

bash "${PODS_ROOT}/ScanbotBarcodeScannerSDK/ScanbotBarcodeScannerSDK.framework/strip-SBSDK-Framework.sh"

Script Input File:

${PODS_ROOT}/ScanbotBarcodeScannerSDK/ScanbotBarcodeScannerSDK.framework.dSYM

alt text

Android#

Scanbot Barcode Scanner SDK uses native libraries under the hood and supports the following ABIs: armeabi-v7a, arm64-v8a, x86 and x86_64.

By default the native libraries of all these architectures will be included in the app package (APK), which will result in a big APK file. Please consider removing support for x86 and x86_64 architectures. In most cases both โ€œx86โ€ architectures can be removed for the release (production) build, since they are only used on emulators and on some rare devices with the Intel Atom architecture.

To exclude certain ABIs from the APK, use the abiFilters property in the Android Gradle settings of your project.

Please check and adjust the abiFilters configuration in your build.gradle file accordingly:

android {  ...  defaultConfig {    ...    ndk {      // a typical production configuration:      abiFilters "armeabi-v7a", "arm64-v8a"    }  }}

๐Ÿ’ก However, if you need to support all architectures and to optimize the APK size, we highly recommend checking out the Android App Bundle approach. It allows you to create and distribute dedicated and smaller APKs via the PlayStore (basically it is similar to the iOS App Store approach).