How to implement a QR Scanner in Ionic

This tutorial will implement the Ionic Native QR Scanner, which uses cordova-plugin-qrscanner, and add a Frame to the camera view to guide the user to position the QR code correctly so that it can be scanned.

1. Install the QR Scanner

$ ionic cordova plugin add cordova-plugin-qrscanner
$ npm install --save @ionic-native/qr-scanner
  • In app.module.ts, import QRScanner and add it to the providers
import { QRScanner } from '@ionic-native/qr-scanner';

providers: [
  QRScanner,
  … ],

2. Create a custom CSS class

When the scanner is active the camera feed will be displayed behind the app. The ion-app and ion-content elements will need to be transparent so that camera feed can be shown in the app.

In some cases, such as when the scanner is on a tabbed page, there is .nav-decor div, which also needs to be made transparent. This is an issue that has been discussed in the Ionic Framework forum.

ion-app.cameraView, ion-app.cameraView ion-content, ion-app.cameraView .nav-decor {
  background: transparent none !important;
}

I have created a cameraView class that can be applied to ion-app to make the 3 elements transparent.

3. Implement the QR Scanner

  • Create a page
$ ionic generate page qr-scanner
  • Import QRScanner and QRScannerStatus
import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner';
  • Create a scanSubscription variable to store the subscription to the scanner
  • Create a scan function to start scanning, which will do the following:
    • Apply the cameraView css class to make the backgrounds transparent
    • All the QRScanner prepare() function, which will request camera permission and prepare for scanning
    • Show the camera feed
    • Subscribe to the scanner results, using the scanSubscription variable to store the subscription
    • Display a toast containing the text from a scanned qr code
    • If camera access was not authorised, output the camera status to the console
    • If any error occurs when scanning, output the error to the console
scanSubscription;

scan() {
  (window.document.querySelector('ion-app') as HTMLElement).classList.add('cameraView');
  this.qrScanner.prepare()
    .then((status: QRScannerStatus) => {
      if (status.authorized) {
        this.qrScanner.show();
        this.scanSubscription = this.qrScanner.scan().subscribe((text:string) => {
          let toast = this.toastCtrl.create({
            message: `${text}`,
            position: 'top',
            duration: 3000,
            closeButtonText: 'OK'
          });
          toast.present();
        });
      } else {
        console.error('Permission Denied', status);
      }
    })
    .catch((e: any) => {
      console.error('Error', e);
    });
}
  • Create a stopScanning function to stop scanning, which will do the following:
    • Unsubscribe from scanSubscription and set it to null
    • Remove the cameraView css class to put the backgrounds back to their original style
    • Hide the camera feed
    • Stop using the camera. destroy() function was added in ionic-native 4.3.0
stopScanning() {
  (this.scanSubscription) ? this.scanSubscription.unsubscribe() : null;
  this.scanSubscription=null;
  (window.document.querySelector('ion-app') as HTMLElement).classList.remove('cameraView');
  this.qrScanner.hide();
  this.qrScanner.destroy();
}
  • Call scan() when you go to the qr-scanner page
  • Call stopScanning() function you leave the qr-scanner page
ionViewWillEnter() {
  this.scan();
}
ionViewWillLeave() {
  this.stopScanning();
}
  • Add the page to your app

4. Add a scanner frame to the camera

  • Download this image of a QR Scanner frame
  • Import the image into the project in the assets/img/ directory
  • Add the image to the page content
<ion-content>
  <img src="assets/img/softwarb_qr_scanner_white.png" alt="">
</ion-content>
  • Add some styling to the image to centrally align it and reduce the opacity of the frame
page-qr-scanner {
  img {
    opacity: 0.5;
    max-width: 95%;
    max-height: calc(98% - 100px);
    position: fixed;
    top: 50%;
    left: 50%;
    /* bring your own prefixes */
    transform: translate(-50%, -50%);
  }
}

5. Result

You will be able to use the QR Scanner in your Ionic app

IDme QR Scanner screenshot

Related: How display a Customised QR Code in your Ionic App

Leave a Comment

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