Skip to content

How to integrate our Capacitor Barcode Scanner SDK – in just a few minutes

With the Scanbot SDK’s RTU UI, integrating barcode scanning functionalities into your Capacitor app is a breeze. We’ll show you how it works.

Marko September 23, 2024 8 mins read
app store

Setting up an app in Ionic Capacitor capable of scanning any 1D or 2D barcode is very straightforward. All we need are the following steps:

  1. Prepare the project
  2. Install the SDK
  3. Initialize the SDK
  4. Implement the scanning modules
  5. Scan some barcodes!

Thanks to our SDK’s Ready-to-Use UI Components, you can even use an AR overlay to display multiple barcodes’ contents right in the viewfinder.

Requirements

Before starting development with Capacitor, you need to set up your environment.

The prerequisites for developing Ionic Capacitor apps are:

Core requirements:

  • Node.js version 18 or higher

For iOS development:

  • macOS
  • Xcode
  • Xcode Command Line Tools
  • Homebrew
  • Cocoapods

For Android development:

  • Android Studio
  • Android SDK

To get the full benefits and experience from using our SDK, we also recommend real devices for testing.

Developing Capacitor applications can be done via CLI or using the VS Code extension. In this tutorial we will use CLI commands. However, feel free to follow along using whatever option suits you best.

Capacitor can be used with different frameworks. In this tutorial, we will use Capacitor with Ionic and Angular. Again, these choices depend on your needs and prior knowledge.

Since we’ll use Ionic in this tutorial, you also need to install the Ionic CLI if you haven’t already:

npm install -g @ionic/cli

1. Preparing the project

To start creating your Capacitor app with Ionic using the CLI, run the following command in the terminal, which will create a blank project with some recommended Capacitor dependencies:

ionic start CapacitorTutorial blank --capacitor --type angular-standalone --package-id io.scanbot.tutorial.capacitor

⚠️ When using your own license, make sure that the package-id is the same as the application/bundle ID associated with it.

Generate the native projects

Now, let’s add the Android and iOS platforms to our project.

Navigate into the project directory:

cd CapacitorTutorial

Add Android and iOS as platforms:

npm i @capacitor/android @capacitor/ios

Run the following commands to create the native Android and iOS projects:

npx cap add android
npx cap add ios

2. Installing the SDK

To install the Scanbot Capacitor Barcode Scanner SDK, run:

npm i capacitor-plugin-scanbot-barcode-scanner-sdk

💡 This will install the latest Scanbot SDK version. You can find more information about each version in our changelog.

Now that the npm package has been installed, we need to make some changes to the native projects.

Android

For Android, we need to add the camera permission and feature in android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />

iOS

For iOS, we need to include a description for the camera permission in ios/App/App/Info.plist anywhere inside the <dict> element:

<key>NSCameraUsageDescription</key>
<string>Camera permission is needed to scan barcodes</string>

Now that the project is set up, we can start integrating the barcode scanning functionalities.

3. Initializing the SDK

Before using any feature of the Capacitor Barcode Scanner SDK, we need to initialize it. Ideally, initialization should be done once, as soon as the app is fully launched.

In this tutorial, we’re going to initialize the SDK inside the ngOnInit callback in the src/app/app.component.ts file and make sure that we import the ScanbotBarcodeSDK. Your app.component.ts should then look like this:

import { Component, OnInit } from '@angular/core';
import { IonApp, IonRouterOutlet } from '@ionic/angular/standalone';

import { ScanbotBarcodeSDK } from 'capacitor-plugin-scanbot-barcode-scanner-sdk';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  standalone: true,
  imports: [IonApp, IonRouterOutlet],
})
export class AppComponent implements OnInit {
  constructor() { }

  ngOnInit(): void {
    ScanbotBarcodeSDK.initializeSdk({
      licenseKey: ""
    }).then(result => console.log(result))
      .catch(err => console.log(err));
  }  
}

💡 Without a license key, our SDK only runs for 60 seconds per session. This is more than enough for the purposes of our tutorial, but if you like, you can generate a license key using the application/bundle ID.

4. Implementing the scanning modes

Our RTU UI components make it easy to deploy our Barcode Scanner SDK’s different scanning modes in your app. Let’s start with the simplest use case: single-barcode scanning.

In your project folder, go to scr/app/home/home.page.ts, add the necessary imports, and create a method that will start the single-barcode scanning use case. The result should look something like this:

import { Component } from '@angular/core';
import { IonHeader, IonToolbar, IonTitle, IonContent, IonButton } from '@ionic/angular/standalone';
import { ScanbotBarcodeSDK } from 'capacitor-plugin-scanbot-barcode-scanner-sdk';
import { startBarcodeScanner, BarcodeScannerConfiguration, SingleScanningMode } from 'capacitor-plugin-scanbot-barcode-scanner-sdk/ui_v2';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
  standalone: true,
  imports: [IonHeader, IonToolbar, IonTitle, IonContent, IonButton],
})
export class HomePage {
  constructor() {}

  async startSingleBarcodeScan() {
    try {
        /** Check license status and return early if the license is not valid */
        if (!(await ScanbotBarcodeSDK.getLicenseInfo()).data?.isLicenseValid) {
            return;
        }
        /**
         * Instantiate a configuration object of BarcodeScannerConfiguration and
         * start the barcode scanner with the configuration
         */
        const config = new BarcodeScannerConfiguration();
        /** Initialize the use case for single scanning */
        config.useCase = new SingleScanningMode();
        /** Start the BarcodeScanner */
        const result = await startBarcodeScanner(config);
        /** Handle the result if there are scanned barcodes */
        if (result.data && result.data?.items.length > 0) {
            alert(
                'Barcode Scanning successfully! \n' +
                `Value: ${result.data.items[0].text} \n` +
                `Type: ${result.data.items[0].type}`
            );
        }
    } catch (e: any) {
        console.error("An error has occurred while running Barcode Scanner", e.message);
    }
  }
}

Next, go to scr/app/home/home.page.html and add a button that calls our startSingleBarcodeScan method when clicked. Your home.page.html should look something like this:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Capacitor Tutorial
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-header collapse="condense">
    <ion-toolbar>
      <ion-title size="large">Capacitor Tutorial</ion-title>
    </ion-toolbar>
  </ion-header>

  <div id="container">
    <ion-button (click)="startSingleBarcodeScan()">Start single barcode scanning</ion-button>
  </div>
</ion-content>

We can add our multi-scanning and AR overlay use cases in a similar manner.

Just add MultipleScanningMode to the import:

import { startBarcodeScanner, BarcodeScannerConfiguration, SingleScanningMode, MultipleScanningMode } from 'capacitor-plugin-scanbot-barcode-scanner-sdk/ui_v2';

And create two more methods:

async startMultiBarcodeScan() {
  try {
    /** Check license status and return early if the license is not valid */
    if (!(await ScanbotBarcodeSDK.getLicenseInfo()).data?.isLicenseValid) {
      return;
    }
    /**
     * Instantiate a configuration object of BarcodeScannerConfiguration and
     * start the barcode scanner with the configuration
     */
    const config = new BarcodeScannerConfiguration();
    /** Initialize the use case for multi-scanning */
    config.useCase = new MultipleScanningMode();
    /** Start the BarcodeScanner */
    const result = await startBarcodeScanner(config);
    /** Handle the result */
    if (result.data && result.data?.items.length > 0) {
      alert(
        'Barcode Scanning successfully! \n' +
        `${result.data.items.map(barcode =>
          `Barcode value: ${barcode.text} and type: ${barcode.type}`
        ).join("\n")}`);
    }
  } catch (e: any) {
    console.error("An error has occurred while running Barcode Scanner", e.message);
  }
}

async startAROverlayBarcodeScan() {
  try {
    /** Check license status and return early if the license is not valid */
    if (!(await ScanbotBarcodeSDK.getLicenseInfo()).data?.isLicenseValid) {
      return;
    }
    /**
     * Instantiate a configuration object of BarcodeScannerConfiguration and
     * start the barcode scanner with the configuration
     */
    const config = new BarcodeScannerConfiguration();
    /** Initialize the use case for multi-scanning */
    config.useCase = new MultipleScanningMode();
    /** Configure AR Overlay. */
    config.useCase.arOverlay.visible = true;
    config.useCase.arOverlay.automaticSelectionEnabled = false;
    /** Start the BarcodeScanner */
    const result = await startBarcodeScanner(config);
    /** Handle the result */
    if (result.data && result.data?.items.length > 0) {
      alert(
        'Barcode Scanning successfully! \n' +
        `${result.data.items.map(barcode =>
          `Barcode value: ${barcode.text} and type: ${barcode.type}`
        ).join("\n")}`);
    }
  } catch (e: any) {
    console.error("An error has occurred while running Barcode Scanner", e.message);
  }
}

Next, go back to scr/app/home/home.page.html and add buttons for the multi-scanning and AR overlay use cases:

<ion-button (click)="startMultiBarcodeScan()">Start multi-barcode scanning</ion-button>
<ion-button (click)="startAROverlayBarcodeScan()">Start AR Overlay barcode scanning</ion-button>

We’re now ready to build and run the app!

5. Build the app and scan some barcodes!

In the terminal, run these commands to build and sync the native projects:

npm run build
npx cap sync

To run the app on Android and iOS, use the following commands:

For Android:

npx cap run android

For iOS:

To run the app on a real iOS device, you need to adjust the Provisioning and Signing settings. Open ios/App/App.xcworkspace with Xcode, manage the signing and provisioning settings, and run the project from Xcode or with this command:

npx cap run ios

Now you can go ahead and scan 1D and 2D barcodes – one after the other, many at the same time, and even with an AR overlay that lets you preview their values!

And if you’re in need of some sample barcodes for testing purposes, we’ve got you covered:

Various barcodes for testing

Conclusion

If this tutorial has piqued your interest in integrating barcode scanning functionalities into your Ionic Capacitor app, make sure to take a look at our SDK’s other neat features in our documentation.

Furthermore, you can take a look at and run our public example project.

Should you have questions about this tutorial or ran into any issues, we’re happy to help! Just shoot us an email via tutorial-support@scanbot.io.

Happy coding!