Scanning QR code is one of the important features to add in your application, because that will give it more value. QR code and Barcode scanning is so useful especially in mobile apps because they solve a lot of problems that we will be talking about in this article.
In this article we implement QR code and Barcode scanning fuctionality with Ionic 6. We will access our mobile’s camera in order to scan and read data from a QR code or a Barcode
Before starting the development of the app, you will need to install Ionic in your computer and then setup a new Ionic 6 project.
Obviously, most of people reading this blog know what is Ionic and how it works, but there also are people who are just starting in Ionic development so that is why I’m explaining the technology.
Ionic is an open source JavaScript framework that was created in 2013 by Max Lynch and Ben Sperry. It is a mobile toolkit used for building high quality cross platform mobile applications using web development technologies such as HTML, CSS, JavaScript, Angular, React…
The best advantage of Ionic is the possibility to generate apps for multiple platforms (Android, IOS, Windows, Web…) with a single code base.
If you want to build a mobile app natively, you will have to use Java or Kotlin in Android and Swift or Objective-c for IOS which means you will write two different projects which won’t be easy. In the other hand, you can use cross platform technologies such as Ionic to develop your mobile app for all platforms you want with a single code base.
QR codes and Barcodes are so useful in many cases, for example when you go to a supermarket or you have a delivery from amazon or any other company you need to check if the product is yours or not. The old way to manage this is to enter the Barcode with your hand which is so boring, if you have a mobile app with the scanning functionality, all you need to do is to turn on your camera and scan the Barcode. We can also use QR code in a restaurant from the table to order food just by scanning the QR code, and there are many other use cases of using QR code and Barcode that you can find in the following section.
Barcode is a series of numbers with set of black and white lines that is usually used to identify a product. When you scan the Barcode of a product you get a lot of information such as the price of the product. Some new mobile phones give you the possibility to scan a Barcode from the camera itself without using any mobile app.
Capacitor is a run-time app that helps build high quality cross-platform mobile apps. It makes it easy to build web applications and run them natively in several platforms such as Android, IOS, Web, Desktop (using Electron). Capacitor was created in 2019 by the Ionic framework team in order to solve some problems in Cordova.
Cordova has actually similar to capacitor, it is an open source framework that makes it easy for web developers to use HTML, CSS, JavaScript and build native mobile applications for many different devices. It was created in 2008 by some software engineers in Nitobi company in Canada.
Capacitor and Cordova are similar and they have the same purpose at the end, but there are some differences between both of them.
Capacitor have have a big advantage over cordova which is the support of Progressive web applications. They also have a big collection of tools that makes it easy to access some native APIs like the Camera API, so it was implemented like a native application. Capacitor will use your web implementations only when the native ones does not exist, and this way the generated mobile app will be so performant and so fast.
Cordova is a great framework as well, it provides everything you need to build mobile applications using web dev technologies. It can access native API in any device such as Camera, Microphone…
In this section which is the most important one in this article, we will have a look into QR Code/Barcode scanning feature implementation in Ionic step by step. Before starting, make sure you have installed Ionic in your computer.
In this project we will use Cordova to implement the Scanning feature.
Setting up an Ionic project is such an easy task, you will need to run a single command to do that.
ionic start QRCode-Barcode-scanner blank –cordova
This command will create a new Ionic 6 project with Cordova integration and with Angular project structure which is the default option in Ionic.
In order to run the project. Run the following command :
ionic serve
In order to implement this feature we need some very important cordova packages that will make it easy for us to implement the functionality.
Run the following command to install the packages
ionic cordova plugin add cordova-plugin-qrscanner
npm install @ionic-native/qr-scanner
The installed packages have to be declared in our application. We have to import some modules in app.module.ts file to achieve that.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { QRScanner } from '@ionic-native/qr-scanner/ngx';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, ],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }, QRScanner],
bootstrap: [AppComponent],
})
export class AppModule {}
And also in the home.page.ts as a service. Have a look to the following code
The following snippet of code is a template to display some content with the scan button, you can add it to your home.page.html file.
<ion-header>
<ion-toolbar>
<ion-title>
Scan your QR Code
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<div class="ion-padding">
<ion-button (click)="startScanning()" expand="full">
Scan
</ion-button>
<p *ngIf="qrContent">QR Scan text: {{ qrContent }}</p>
</div>
</ion-content>
Now, we implement the QR Code/Bar code scanning methods in home.page.ts file which will be triggered when scanning the QR code with the camera. Copy and paste the following code in your home.page.ts file
import { Component } from '@angular/core';
import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner/ngx';
import { Platform } from '@ionic/angular';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
scanSub: any;
qrContent: string;
constructor(
public platform: Platform,
private qrScanner: QRScanner
) {
this.platform.backButton.subscribeWithPriority(0, () => {
document.getElementsByTagName('body')[0].style.opacity = '1';
this.scanSub.unsubscribe();
});
}
startScanning() {
this.qrScanner.prepare().
then((status: QRScannerStatus) => {
if (status.authorized) {
this.qrScanner.show();
this.scanSub = document.getElementsByTagName('body')[0].style.opacity = '0';
debugger
this.scanSub = this.qrScanner.scan()
.subscribe((textFound: string) => {
document.getElementsByTagName('body')[0].style.opacity = '1';
this.qrScanner.hide();
this.scanSub.unsubscribe();
this.qrContent= textFound;
}, (err) => {
alert(JSON.stringify(err));
});
} else if (status.denied) {
} else {
}
})
.catch((e: any) => console.log('Error is', e));
}
}
There are many options that the scan method take, let’s understand them together :
preferFrontCamera : false ⇒ This option will open the back camera of the phone
showFlipCameraButton : true ⇒ This option make sure that the possibility of changing from front to back camera possible.
torchOn: false ⇒ Android, launch with the torch switched on (if available)
saveHistory: true ⇒ Android, save scan history
prompt : “Place a code inside the scan area”,
resultDisplayDuration: 500 ⇒ Android, display scanned text for X ms. 0 suppresses it entirely, default 1500
formats : “EAN_13,EAN_8,QR_CODE,PDF_417”, // default: all but PDF_417 and RSS_EXPANDED
orientation : “portrait”, // Android only (portrait|landscape), default unset so it rotates with the device
Now that we implemented the QR Code scanning functionality, let’s test our app and see the result. We will build our application for both platforms Android and IOS.
Starting with Android, cordova have some great integrations such as building a mobile application by running one single command.
ionic cordova platform add android
And now let’s run our application in android studio using the following command.
ionic cordova run android
Congratulations, you have successfully implemented the scanning functionality in the Android platform. Click on the scan code button and you will get your camera opened to scan the QR Code.
For IOS go to config.xml file and add the following snippet of code in there.
<edit-config target="NSCameraUsageDescription" file="*-Info.plist" mode="merge">
<string>To scan barcodes</string>
</edit-config>
Scanning QR Codes and Barcodes is very important feature that is used very often in mobile applications. Learning how to do it as a mobile app developer will really help you increase the value of your skills. So make sure you road the whole article very carefully to get the most of it.
We got more interesting blog posts about mobile and web development, if you are interested take a look on our blog posts home page.
If you want to know more about how to build an offline mobile application with Ionic 6 check out this blog
Thank you so much for reading.