Ionic 5|4 Add Barcode/ QR Code Scanner/ Encoder Generator using Native Plugin

In this tutorial, we will implement a Barcode or QR Scanner / Encoder plugin in an Ionic application. Barcodes and QR codes are widely used for multiple purposes like to add a link where a user doesn’t need to type the whole URL it can be easily scanned from a QR code. Barcodes can also…

By.

•

min read

In this tutorial, we will implement a Barcode or QR Scanner / Encoder plugin in an Ionic application. Barcodes and QR codes are widely used for multiple purposes like to add a link where a user doesn’t need to type the whole URL it can be easily scanned from a QR code. Barcodes can also be seen everywhere on the day to day items like eatables clothes etc, we can wimple scan these barcodes to get information like item code date of manufacturing, prices, etc.

We will create a similar app to scan these codes.

Using React? Check this tutorial to implement Barcode Scanner in Ionic React

 

Let’s start…

 

Version Check

@ionic/cli 

   _             _
  (_) ___  _ __ (_) ___
  | |/ _ \| '_ \| |/ __|
  | | (_) | | | | | (__
  |_|\___/|_| |_|_|\___| CLI 6.4.1

# Update Ionic CLI

Run following npm command to update the Ionic CLI tool to the latest version

$ npm install -g @ionic/cli</pre>
 
<h3># Create new Ionic application:</h3>
Execute the following command to create a new Ionic Angular application with a <code>blank template:
$ ionic start ionic-ng-barcode-demo blank --type=angular
</pre>
then move to the root path of the application
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ cd ionic-ng-barcode-demo</pre>
<h4></h4>
<h3># Install the Cordova and Ionic Native plugins:</h3>
Next, we will install Cordova and Ionic Native plugin wrapper to use Bar Code Scanner and Generator in the application. Run following commands in the terminal at the application root:
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ionic cordova plugin add phonegap-plugin-barcodescanner
$ npm install @ionic-native/barcode-scanner</pre>
<h4></h4>
<h4># Update Application's App Module</h4>
To use Native features, open the <strong>app.module.ts</strong> file to import the <code>BarcodeScanner class then update providers array as shown below:
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule, 
    FormsModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    BarcodeScanner,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Above we have added FormsModule in imports, array to use form elements later.

Also Check: Ionic 4 | Adding Barcode / QR Code Scanner in Ionic 4 Application using ZBar Cordova and Native Plugin

# Implement Barcode/ QR Code Scanner and Generator

The BarcodeScanner class provides two main methods, the scan() is used to scan an Image of Bar or QR code image using the device camera and the encode() method takes the string to convert into a QR code.

For adding configuration, import the BarcodeScannerOptions interface. We will discuss various options available later in this tutorial.

Update the home.page.ts file with the scanBar() and generateBar() methods.

import { Component } from "@angular/core";
import {
BarcodeScannerOptions,
BarcodeScanner
} from "@ionic-native/barcode-scanner/ngx";

@Component({
selector: "app-home",
templateUrl: "home.page.html",
styleUrls: ["home.page.scss"]
})
export class HomePage {
encodeData: any;
scannedData: {};
barcodeScannerOptions: BarcodeScannerOptions;

constructor(private barcodeScanner: BarcodeScanner) {
this.encodeData = "https://www.FreakyJolly.com";
//Options
this.barcodeScannerOptions = {
showTorchButton: true,
showFlipCameraButton: true
};
}

scanCode() {
this.barcodeScanner
.scan()
.then(barcodeData => {
alert("Barcode data " + JSON.stringify(barcodeData));
this.scannedData = barcodeData;
})
.catch(err => {
console.log("Error", err);
});
}

encodedText() {
this.barcodeScanner
.encode(this.barcodeScanner.Encode.TEXT_TYPE, this.encodeData)
.then(
encodedData => {
console.log(encodedData);
this.encodeData = encodedData;
},
err => {
console.log("Error occured : " + err);
}
);
}
}
</pre>
The <code>BarcodeScannerOptions
defines options like to show torch button, show button to flip camera front or back.

# Update Home Template

Now we will add a button to start scan and show encoded text, also we have added a text field where a user can input a string which can be generated into a QR Code.

In home.page.html, add a button and show the result of scanned Barcode, having text information bar type.

<ion-header [translucent]="true">
<ion-toolbar>
<ion-title>
Ionic QR/ Barcode Scanner
</ion-title>
</ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true" class="ion-padding">
<h1>Click Button To Scan</h1>

<ion-button color="primary" (click)="scanBar()">
Scan Code
</ion-button>

<div *ngIf="scannedData">
<p>
Scanned Code Text : <b>{{ scannedData["text"] }}</b>
</p>
<p>
Scanned Code Format : <b>{{ scannedData["format"] }}</b>
</p>
</div>

<h1>Enter Value to Create QR code</h1>
<ion-input placeholder="Enter Input" [(ngModel)]="encodedData"></ion-input>

<ion-button color="success" (click)="generateBar()">
Create QR
</ion-button>
</ion-content></pre>
Now you have a working Bar and QR scanner application which can also generate QR code by taking a user input string.

 
<h3># How to test the application?</h3>
To test this application you need to run the app in a real device. Just run following command after connecting your mobile device to the computer via USB wire.

<code>$ ionic cordova run android -l

Note: Sometimes you may see an error like this:

[ERROR] Could not parse build output file: platforms\android\app\build\outputs\apk\debug\output.json

Try creating the app-debug.apk first by running

$ ionic cordova build android

You can generate QR codes online here

See mine :P

 

Source Code link on GitHub

In this tutorial, we have created a sample app to scan Barcode and QR code using Cordova plugins in Ionic Native.

20 responses to “Ionic 5|4 Add Barcode/ QR Code Scanner/ Encoder Generator using Native Plugin”

  1. Vadim Avatar
    Vadim

    •

    Jolly, thank you!
    To run this command “ionic cordova build android”, do i need to have installed:
    • Android Studio;
    • Android Studio SDK;
    • Java 8 SDK
    ?

    1. Nikky Avatar
      Nikky

      •

      If i remember correctly – you don’t need android studio; just gradle and JDK.
      When you run the command to build; cordova will handle the rest provided that you have set Gradle bin path and JDK bin path into system env.

  2. joao vitor Avatar
    joao vitor

    •

    how do I get the string of the link that was scanned? I need to put it in an array of strings

  3. BlaqPrynx Avatar
    BlaqPrynx

    •

    wow i really love this …Jolly you are the man it actually worked for me when i used the ionic devApp to try….. But my problem is it only shows the number…..how can i get details like the name of the product ,manufacturing date or the expiring date of the product……………..but really its a GoodWork out there….God Bless you…….will be looking forward to hear from you soon

  4. karol Avatar
    karol

    •

    hello, i have a problem, when I scann the code, the app show and alert: barcode data{“text”:”www.facebook.com\n.”,”format”:”QR_CODE”,”cancelled”:false}

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hi Karol, this is the expected behavior to scan and return a response in the JSON object. Can you explain your problem a bit more?

  5. Pichit W Avatar
    Pichit W

    •

    Hello Jolly, I’ve try this project then show the problem about ‘Cannot find module ‘node-sass’ ‘ with npm v 6.8.0. How can I fix this?
    Thanks.

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hi Pichit, as searched in Google I found this Let me know if it helped 🙂

  6. Szymon Kiciński Avatar

    Hello, could you please share this code on e.g. GitHub? Thanks! 🙂

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hello Szymon Kiciński,

      Please check Github source link updated in the post.

      Thanks
      Jolly

  7. Christopher Solís Avatar

    Hi Jolly. I’m having a problem when I try to open the camera to read the QR code that every time I press the button it doesn’t do anything.

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hi Christopher, try the source code link updated in post and let me know if it’s working fine

Leave a Reply

Your email address will not be published. Required fields are marked *