Ionic 4/5 Cordova Barcode Scanning Plugin Tutorial with Example

INTRODUCTION


In this tutorial, we'll talk about how to add a Barcode or QR Scanner/Encoder plugin to an Ionic/Angular application.  Barcodes and QR codes are used for a lot of different things. For example, a QR code can add a link, so the user doesn't have to type the whole URL. Barcodes can also be found on food, clothes, and other everyday items. We can scan these barcodes to get information like the item code, the date it was made, prices, etc. I hope you already know what Ionic is and how it works. We'll use CLI, HTML, CSS, TS, etc.

  • Step 1 — Ionic/Angular application
  • Step 2 — Setup barcodescannerplugin
  • Step 3— Use barcodescanner  Plugin In App
  • Step 4 — Build the application in real time for Android & Test
  • Step 5— Various barcodescanner  Plugin Features

So let’s dive right in!


STEP 1 — Ionic/Angular GETTING STARTED

After ensuring you have the latest versions of Ionic and Cordova installed, let's create an app and add authentication.

To get started, let's make a new app. Open your Terminal or Command Prompt and go to the directory where you want to create the app. Following command can change the cmd directory.

cd Desktop/ 

For new project:

ionic start uniqueAppName blank --type=angular --spec false

Next, open the "uniqueAppName" project folder.

cd uniqueAppName/

Ionic/Angular application has been created successfully.  


Step 2 — Let's Start

To access barcodescanner in our Ionic Application, we need to install barcodescanner plugin first in our application. To install barcodescanner plugin run these command in your ionic project by terminal:

ionic cordova plugin add phonegap-plugin-barcodescanner
npm install @ionic-native/barcode-scanner

Now, add the Barcode module to your in your project. Open app.module.ts and then add it into the provider. This lets you use it as a dependency injection in the constructor of the page and use it in all of the app's parts.

..., // Other imports
import { BarcodeScanner } from '@ionic-native/barcode-scanner/ngx';

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

Now we can use this plugin inside our app pages. So we are gonna creating buttons which upon clicking, we will trigger function on scanning or creating qrcode. Now headover to the home.page.html file and create ion-button like this:

<ion-button (click)="onCreateBarCodeScanner()">
Create Barcode
</ion-button>
<ion-button (click)="onScanBarCodeScanner()">
Scan Barcode
</ion-button>

Now in home.page.ts file, we are gonna implement these two functions and upon clicking we are going to scan and create qrcode by our ts barcodescanner  plugin. So lets implement on these function. in home.page.ts file:

scannedData: any;
encodedData: '';
encodeData: any;
constructor(public barcodeScan: BarcodeScanner) { }

onScanBarCodeScanner() {
const options: BarcodeScannerOptions = {
        formats: 'QR_CODE,PDF_417 ',
orientation: 'landscape',
preferFrontCamera: true,
torchOn: false,
prompt: 'Put a barcode in the area that can be scanned.',
resultDisplayDuration: 500,
        showFlipCameraButton: true,
showTorchButton: true,
};
     this.barcodeScan.scan(options).then(barCode => {
console.log('Scanned data: ', barCode);
this.scannedData = barCode ;

}).catch(err => {
console.log('Error', err);
});
}

onCreateBarCodeScanner() {
this.barcodeScan.encode(this.barcodeScan.Encode.TEXT_TYPE, this.encodeData).
       then((enCoded) => {
console.log(enCoded);
this.encodedData = enCoded;
}, (err) => {
console.log('Error :' + err);
});
}

This function will turn on the phone's camera and let you scan a barcode. It will then tell you whether you were successful or not. If it works, the scan data object we are storing in a variable will be written to the console log. It will log an error to the console if it throws an error.

In the scan({options}) function, you can also pass an options object. These are:

preferFrontCamera : true, / true or false
showFlipCameraButton : true, // true or false
showTorchButton : true, // true or false
torchOn: true, // true or false
saveHistory: true, // true or false
prompt : 'Put a barcode in the area that can be scanned.',
resultDisplayDuration: 500, // Display scanned text formats : 'QR_CODE,PDF_417', // Format orientation : 'landscape', // Works On Android only portrait|landscape), default unset

This plugin will need a camera and the ability to save files on the device, so make sure your device has both. Since iOS 10, adding NSCameraUsageDescription is required.

NSCameraUsageDescription explains why the app needs to use the user's camera. This string is shown in the dialogue box that asks the user if they want to allow access. If you didn't give the usage description, the app will crash before showing the dialogue. Apple will also reject apps that access private information but don't explain how they will be used.

Now with this, we are done. We successfully created simple barcode scanner and creater in our Ionic App. So, we can't check it browser, so to test this, we will build our app first and run this on a real device. To build application:

$ ionic cordova build android --aot --prod

Thanks for reading. Subscribe to us on YouTube.

Tags

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !