Follow

Cordova - Using Cordova 6.x with Ionic

The Ionic framework is supported by Scandit technology and the purpose of the following article is to facilitate the integration and setting up of your Ionic application alongside Scandit SDK.

Create a new project (optional)

If you still do not have an Ionic project that you will use, you should create a new one.

$ ionic start helloscandit --cordova
$ cd helloscandit

Add the platform(s)

To add a platform to the project, run either one or both of the following commands:

$ ionic cordova platform add ios
$ ionic cordova platform add android

Please note: If you add the iOS platform, you need to open the generated Xcode project and setup signing. After this is done, you can close Xcode and run the sample as explained below.

Add the Scandit Data Capture SDK for Cordova

> For 6.5+ versions of our Cordova plugins, please follow the steps described in the documentation here.

> For 6.7+ versions of our Cordova plugins that use Android platform, please run additionally the two below commands (action is required because ionic project needs to use AndroidX with 6.7+ versions): 

$ ionic cordova plugin add cordova-plugin-androidx
$ ionic cordova plugin add cordova-plugin-androidx-adapter

> For 6.3.2 – 6.5 versions of our Cordova plugins, there might be a dependency conflict caused by the fact that our Cordova plugin requires WkWebView as well as Ionic does. Please follow the steps listed below to be able to add our Cordova plugin with a removed dependency:

1. Download our Scandit Cordova 6.x plugin from the Scandit dashboard and put it (unzipped) in the project’s folder. 

2. Delete the following line in the plugin.xml file of our Core plugin you downloaded (project_root/scandit-datacapture-cordova-6.x/scandit-cordova-datacapture-core/plugin.xml)

<dependency id="cordova-plugin-wkwebview-engine" version="1.1.4"/>

3. Use the Cordova CLI to add the scandit-cordova-datacapture-core plugin:

$ ionic cordova plugin add <path to scandit-cordova-datacapture-core plugin>

4. Use the Cordova CLI to add the scandit-cordova-datacapture-barcode plugin:

$ ionic cordova plugin add <path to scandit-cordova-datacapture-barcode plugin>

 Please note: If you have already added our plugins in any other way before, please make sure to follow Cordova best practices and remove the plugin before adding the working version:

$ ionic cordova plugin remove <id of the plugin being updated>

After following the steps above, run the following command to recreate dependencies of your project:

$ ionic repair

Add files / snippets to connect SDK with your app

Please note: The following steps are not a requirement to make an Ionic based project work with our plugin, but rather a suggestion on how you may get started.

Add scandit.d.ts file (containing all types definitions used by our library) in src directory of your app:

type Barcode = {
  data: string,
  symbology: string,
}

type Point = {
  x: number,
  y: number,
}

type Quadrilateral = {
  topLeft: Point,
  topRight: Point,
  bottomRight: Point,
  bottomLeft: Point,
}

type LocalizedOnlyBarcode = {
  location: Quadrilateral,
  frameID: number,
}

type BarcodeCapture = any;

type BarcodeCaptureSession = {
  newlyRecognizedBarcodes: Barcode[],
  newlyLocalizedBarcodes: LocalizedOnlyBarcode[],
}

interface ScannerDelegate {
  didScan(barcodeCapture: BarcodeCapture, session: BarcodeCaptureSession)
}

declare let Scandit;

 Add scanner-service.ts file (containing code related to interacting with the Scandit Cordova plugin) under src/providers/scanner-service:

import { Injectable, NgZone } from '@angular/core';

@Injectable()
export class ScannerServiceProvider {
  public contentHeight;
  public delegate: ScannerDelegate;

  public barcodeCapture;
  public session;
  private context;
  private camera;
  private settings;
  private view;
  private overlay;

  constructor(
    private zone: NgZone,
  ) {
    this.context = Scandit.DataCaptureContext.forLicenseKey('YOUR_LICENSE_KEY_IS_NEEDED_HERE');
    this.camera = Scandit.Camera.default;
    this.context.setFrameSource(this.camera);

    this.settings = new Scandit.BarcodeCaptureSettings();

    this.settings.enableSymbologies([
      Scandit.Symbology.EAN13UPCA,
      Scandit.Symbology.EAN8,
      Scandit.Symbology.UPCE,
      Scandit.Symbology.QR,
      Scandit.Symbology.DataMatrix,
      Scandit.Symbology.Code39,
      Scandit.Symbology.Code128,
      Scandit.Symbology.InterleavedTwoOfFive,
    ]);
    this.settings.codeDuplicateFilter = -1;
    this.barcodeCapture = Scandit.BarcodeCapture.forContext(this.context, this.settings);
    this.barcodeCapture.applySettings(this.settings)
    this.barcodeCapture.addListener({
      didScan: (barcodeCapture, session) => {
        if (this.delegate) {
          this.zone.run(() => {
            this.delegate.didScan(barcodeCapture, session);
          })
        }
      },
    });
  }

  public start(): void {
    this.view = Scandit.DataCaptureView.forContext(this.context);
    this.view.connectToElement(document.getElementById('scanner'));
    this.overlay = Scandit.BarcodeCaptureOverlay.withBarcodeCaptureForView(this.barcodeCapture, this.view);
    this.overlay.viewfinder = new Scandit.RectangularViewfinder();
    this.camera.switchToDesiredState(Scandit.FrameSourceState.On);
    this.barcodeCapture.isEnabled = true;
  }

  public resume(): void {
    this.barcodeCapture.isEnabled = true;
  }
  public pause(): void {
    this.barcodeCapture.isEnabled = false;
  }
}

For Angular

Import ScannerServiceProvider in the app.module.ts as follows:

import { ScannerServiceProvider } from '../providers/scanner-service/scanner-service';

@NgModule({
  declarations: [... ],
  entryComponents: [],
  imports: [...],
  providers: [
    ...
    ScannerServiceProvider
  ],
  bootstrap: [...]
})
export class AppModule {}

Example single scanning usage

Add the following code in home.page.ts file of your project:

...
import { IonContent } from '@ionic/angular'
import { ScannerServiceProvider } from '../../providers/scanner-service/scanner-service';
@Component({
...
})
export class HomePage implements ScannerDelegate {
  private barcodes: Barcode[] = [];
  private continuousMode: boolean = false;
  private showSingleButton: boolean = true;
  private showSingleDoneButton: boolean = false;
  
constructor(

    public scanner: ScannerServiceProvider,
  ) {
  }

  public startScanning() {
    this.showScanner();
    this.showSingleButton = false;
    this.showSingleDoneButton = false;
    this.scanner.delegate = this;
    this.scanner.start();
  }

  public startContinuousScanning() {
    this.continuousMode = true;
    document.getElementById('scanner').style.bottom = "10%";
    this.startScanning();
  }

  public resumeScanning() {
    this.scanner.resume();
    this.showScanner();
    this.showSingleButton = false;
    this.showSingleDoneButton = false;
  }

  public doneSingle() {
    this.hideScanner();
    this.scanner.pause();
    this.barcodes = [];
    document.getElementById('result').innerHTML = "";
    this.showSingleButton = true;
    this.showSingleDoneButton = false;
  }

  public done() {
    this.barcodes = [];
    document.getElementById('result').style.display = "none";
    document.getElementById('result').innerHTML = "";
    this.showSingleButton = true;
    this.showSingleDoneButton = false;
    this.continuousMode = false;
  }

  public didScan(barcodeCapture: BarcodeCapture, session: BarcodeCaptureSession) {
    this.barcodes = session.newlyRecognizedBarcodes;
    this.hideScanner();
    document.getElementById('result').style.display = "block";
    this.scanner.pause();
    this.showSingleDoneButton = true;
    let scannedBarcode = "Scanned Code:<br><br>" + this.barcodes[0].symbology.toUpperCase() + ": " + this.barcodes[0].data;
    document.getElementById('result').innerHTML = scannedBarcode;
  }

  public ionViewDidEnter(): void {
  }

  public showScanner() {
    document.getElementById('scanner').style.display = "block";
    document.getElementById('result').style.display = "none";
    document.getElementById('result').innerHTML = "";
  }

  public hideScanner() {
    document.getElementById('scanner').style.display = "none";
  }
}

 Add the following code inside the <ion-content> in home.page.html file of your project:

  <div id="result"></div>
  <div id="scanner"></div>
  <ion-button *ngIf="showSingleButton" class="button" mode="ios" (click)="startScanning()">Start Scanning</ion-button>
  <ion-button *ngIf="showSingleDoneButton" class="button" mode="ios" (click)="doneSingle()">Done</ion-button>

 Add the following code in home.page.scss file of your project (optionally):

.button {
  text-align: center;
  position: absolute;
  left: 10%;
  right: 10%;
  top: 50%;
  font-size: 22px;
  transform: translateY(-50%);
}

.button strong {
  font-size: 24px;
  line-height: 26px;
}

.button p {
  font-size: 25px;
  line-height: 22px;
  color: #8c8c8c;
  margin: 0;
}

.button a {
  text-decoration: none;
}

#scanner {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

#result {
  text-align: center;
  position: absolute;
  left: 0;
  right: 0;
  top: 28%;
  font-size: 22px;
}

Please note: Sometimes Ionic app is trying to reference Scandit API before the deviceready event is fired, and which is needed for all Cordova plugins to works. Since this project uses also Ionic and Angular, you can use the following snippet in src/app/main.ts file: 

if ((window as any).cordova) {
console.info('Waiting with bootstrapping...');
console.time('Device was ready in');
document.addEventListener('deviceready', () => {
console.timeEnd('Device was ready in');
console.info('Bootstrapping now...');
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
});
} else {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
}

instead of: 

platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));

For React

As stated on the Ionic React Overview page: There are no plans to support a Cordova integration for Ionic React

Set the license key

Replace YOUR_LICENSE_KEY_IS_NEEDED_HERE with your license key in src/providers/scanner-service/scanner-service.ts

Run the sample on a device

$ ionic cordova run [ios | android] --device

 

 

Was this article helpful?
0 out of 0 found this helpful
Have more questions? Submit a request