https://github.com/ionic-team/ionic
In the previous tutorial I explained how to generate QR Code with Ionic. In this tutorial I will try to show you how to read any QR Code with Ionic and how to parse the data in QR Code.
First, start a simple Ionic application with following command, this command will create a simple Ionic application with starter template.
$ ionic start myApp blank
I will use the Ionic Native Barcode Scanner plugin to scan the barcodes. Barcode Scanner Plugin opens the camera of phone and scans barcodes automatically, then returning scanned data back. You can easily read the raw data by assigning the returned data to a variable. Now download the barcode scanner plugin from NPM with the following commands.
$ ionic cordova plugin add phonegap-plugin-barcodescanner
$ npm install --save @ionic-native/barcode-scanner
Once you have completed downloading the library with NPM, you need to import this library into the app.module.ts file and add it to the providers list.
import { BarcodeScanner } from '@ionic-native/barcode-scanner';
@NgModule({
declarations: [
...
],
imports: [
...
],
bootstrap: [IonicApp],
entryComponents: [
...
],
providers: [
BarcodeScanner,
...
]
})
export class AppModule {}
Once you have imported the libraries, you can start working on the home page to read the barcodes, QR codes etc.
Reading barcodes with Ionic is really easy. You only need to define a variable for scanned data and assign the returned data from scanCode() function to the scanned_code variable.
export class HomePage {
private scanned_code = null;
constructor(public navCtrl: NavController,
private barcodeScanner: BarcodeScanner) { }
scanCode() {
this.barcodeScanner.scan().then(data => {
this.scanned_code = data;
}).catch(err => {
console.log('Error', err);
});
}
}
I just created a scanCode() function and defined a variable(scanned_code) to assign scanned data. I initially defined the scanned_code variable to be null. I have defined this variable as null because if there is no barcode data read from the camera, it will not be shown on the home page. So on the home page only the data read from a real barcode will be displayed.
The scanCode() function is also simple, it just triggers the camera, if there is any data from the barcode, it takes the data and assigns it to the scanned_code variable.
Now, you just need to add a button on the home page to trigger the scanCode() function.
<button (click)='scanCode()' color="dark"><ion-icon name="qr-scanner"></ion-icon></button>
You can test the app on your Android phone with the following commands.
$ ionic cordova build android
I installed my own phone and made a short gif. I just scanned the QR code of my Litecoin wallet on the phone. Yeah, it's working :)
[Ionic Tutorial #1] - QR Code Generator App
https://github.com/hsynterkr/Ionic-QR-Code-Generator-Scanner