QR Code and Barcode Scanning with Ionic & Capacitor

abhijeetrathor2

Abhijeet Rathore

Posted on March 29, 2020

QR Code and Barcode Scanning with Ionic & Capacitor

This post is about scanning QR code or Barcode in your cool new Capacitor Ionic app.

Since this post is a mix of Ionic, Angular and Capacitor, it is possible you landed here by mistake. If you are looking for barcode scanner implementation in

  • Ionic 4 with Angular in Cordova — Read this blog post
  • React Native — Read this blog post
  • Ionic 4 with Angular in Capacitor — Continue reading this post

As you can see from above, there are several options available for Hybrid app development these days, and it is easy to get confused between them. This post is focussed on Ionic framework with Angular as the front-end framework, and Capacitor as runtime and build environment.

Complete code for this tutorial is available on Github repo ionic-capacitor-barcode-scanner

Let’s see a brief intro to each of the included frameworks:

  1. Ionic
  2. Capacitor

(If you already know about the frameworks, skip the next couple of sections)

What is Ionic ?

You probably already know about Ionic, but I’m putting it here just for the sake of beginners. Ionic is a hybrid mobile app development SDK. It provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores to be installed on devices by leveraging Cordova environment.

So, in other words — If you create Native apps in Android, you code in Java. If you create Native apps in iOS, you code in Obj-C or Swift. Both of these are powerful but complex languages. With Cordova (and Ionic) you can write a single piece of code for your app that can run on both iOS and Android (and windows!), that too with the simplicity of HTML, CSS, and JS.

It is important to note the contribution of Cordova/Capacitor in this. Ionic is only a UI wrapper made up of HTML, CSS and JS. So, by default, Ionic cannot run as an app in an iOS or Android device. Cordova/Capacitor is the build environment that containerizes (sort of) this Ionic web app and converts it into a device installable app, along with providing this app access to native APIs like Camera etc.

Capacitor — How is it different from Cordova ?

Cordova helps build Ionic web app into a mobile device installable app. But there are some limitations of Cordova, which Capacitor tries to overcome with a new App workflow.

Capacitor is a cross-platform app runtime that makes it easy to build web apps that run natively on iOS, Android, Electron, and the web. Ionic people call these apps “Native Progressive Web Apps” and they represent the next evolution beyond Hybrid apps.

Capacitor is very similar to Cordova, but with some key differences in the app workflow

Here are the differences between Cordova and Capacitor

  1. Capacitor considers each platform project a source asset instead of a build time asset. That means, Capacitor wants you to keep the platform source code in the repository, unlike Cordova which always assumes that you will generate the platform code on build time
  2. Because of the above, Capacitor does not use config.xml or a similar custom configuration for platform settings. Instead, configuration changes are made by editing AndroidManifest.xml for Android and Info.plist for Xcode
  3. Capacitor does not “run on device” or emulate through the command line. Instead, such operations occur through the platform-specific IDE. So you cannot run an Ionic-capacitor app using a command like ionic run ios . You will have to run iOS apps using Xcode, and Android apps using Android studio
  4. Since platform code is not a source asset, you can directly change the native code using Xcode or Android Studio. This give more flexibility to developers

In essence, Capacitor is like a fresh, more flexible version of Corodva.

Plugins

Cordova and Ionic Native plugins can be used in Capacitor environment. However, there are certain Cordova plugins which are known to be incompatible with Capacitor. For Barcode Scanning functionality, we’ll use the Phonegap Plugin Barcode Scanner.

QR code and Barcode

QR code or barcode scanning is something almost every smartphone user has done at least once. We scan QR codes in supermarkets, on products in general, and oh, Amazon delivery! It’s a very handy way to recognize products instead of entering 16 digit long ID numbers etc. Similarly, reading ID numbers from Passports, etc could be very handy if you are an international hotel owner and require guests to carry passports as IDs.


We scan QR codes in supermarkets, and on products in general

Here are some potential use cases for these plugins in an Ionic 4 app

  • Super market app — QR/barcode scanners can provide product info to users
  • Delivery app — Barcode scan can track/sign off a package
  • Quick access to offers — Scan QR codes and go to a webpage
  • Web authentication of a mobile app — Similar to Whatsapp Web
  • Event app — Scan tickets or events passes

All this can now be done in Ionic apps, with the latest plugins available in Ionic 4 and Capacitor.

Structure of post

I always go step-by-step for readers of all experience level. If you know certain steps, feel free to skip them

Step 1: Create a basic Ionic Angular app

Step 2: Connect Capacitor with your app

Step 3: Setup Barcode Scanner Plugin and functions

Step 4: Build and Test your app on Android

Let’s get started with Ionic Capacitor Barcode scanning !

Step 1 — Create a basic Ionic Angular app

I have covered this topic in detail in this blog.

In short, the steps you need to take here are

  • Make sure you have node installed in the system (V10.16.0 at the time of this blog post)
  • Install ionic cli using npm (my Ionic version is 4.6.0 )
  • Create an Ionic app using ionic start

You can create a blank starter for the sake of this tutorial. On running ionic start ionic-capacitor-barcode-scanner , node modules will be installed. Once the installation is done, run your app on browser using

$ ionic serve

Make slight modifications to the home page as you like. My app’s home page looks like this

Demo home page for capacitor barcode scanning app

Demo home page for capacitor barcode scanning app

Step 2— Integrate Capacitor in the app

Capacitor can be attached to an existing Ionic app as well. To attach Capacitor to your existing Ionic app, run

$ ionic integrations enable capacitor

This will attach Capacitor to your Ionic app. After this, you have to init the Capacitor app with

$ npx cap init YOUR_APP_NAME YOUR_APP_ID

You should already be having YOUR_APP_NAME and YOUR_APP_ID in config.xml . Use the same here, so that there is no mismatch or confusion.

Step 3 — Setup Barcode Scanner Plugin

Install the following packages by executing the following commands

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

Although we are installing a Cordova plugin, it will work equally well with Capacitor. Now import the Barcode module in your projects app.module.ts and then inject it inside the provider.

Code for scanning barcode in Capacitor Ionic — app.module.ts

Now you can inject it as a dependency inside your page’s constructor and access it all over the app components.

After this, you can simply use the following function to complete a scan process.

Code for scanning a barcode in Capacitor Ionic — home.page.ts

This function will open the phone’s camera, allow you to scan a barcode, and in result will provide success or error .

You can also pass an options object in the scan({options}) function. These options are

preferFrontCamera : true, // iOS and Android
showFlipCameraButton : true, // iOS and Android
showTorchButton : true, // iOS and Android
torchOn: true, // Android, launch with the torch switched on (if available)
saveHistory: true, // Android, save scan history (default false)
prompt : "Place a barcode inside the scan area", // Android
resultDisplayDuration: 500, // Android, display scanned text for X ms. 0 suppresses it entirely, default 1500
formats : "QR_CODE,PDF_417", // default: all but PDF_417 and RSS_EXPANDED
orientation : "landscape", // Android only (portrait|landscape), default unset so it rotates with the device

This plugin will, of course, require a camera and file saving access on the device, so take care of that as per your device. Since iOS 10 it’s mandatory to add NSCameraUsageDescription.

NSCameraUsageDescription describes the reason that the app accesses the user's camera. When the system prompts the user to allow access, this string is displayed as part of the dialog box. If you didn't provide the usage description, the app will crash before showing the dialog. Also, Apple will reject apps that access private data but don't provide a usage description.

To add NSCameraUsageDescription entry, you can use the edit-config tag in the config.xml like this:

<edit-config target="NSCameraUsageDescription" file="*-Info.plist" mode="merge">
<string>To scan barcodes</string>
</edit-config>

Let’s go and check what we get on clicking on barcode scan button.

Step 4: Build and Test your app on Android

Before adding a platform, you need to build your Capacitor assets

// Build web assets
$ ionic build

Now add a new platform, in our case — Android

// Add android platform
$ npx cap add android

Sync any changes done to the code in the platform, and then open the default editor for building the app on device

// Copy all changes to Android platform
$ npx cap sync
// Open the project in Android studio
$ npx cap open android

This opens up the Android Studio, and you can build the app on your device. Once built, test the app with different QR codes and Barcodes. Following is what I get when I test on different codes on my laptop


Ionic Capacitor QRcode and Barcode scanning example

Congrats! You have successfully completed a Barcode and QRcode scanner app 🎉 🎉

You can scan a lot of other varieties as well. Following are the types of codes supported by this plugin

Types of codes supported by Phonegap Barcode Scanner plugin

Types of codes supported by Phonegap Barcode Scanner plugin

Conclusion

In this post, we learned how to integrate Barcode scanner and QR Code scanner phonegap-plugin-barcodescanner in Ionic 4 Capacitor apps. This plugin has great documentation and it supports a lot of code varieties to be scanned. Hence it is developers’ first choice in scanning with Ionic apps. Using this, you can easily integrate QRcode or barcode scanning functionality in any of your Ionic Capacitor apps.

Complete code for this tutorial is available on Github repo ionic-capacitor-barcode-scanner

Next Steps

Now that you have learned the implementation of phonegap-plugin-barcodescannerin Ionic Capacitor, you can also try

Ionic React Capacitor

If you need a base to start your next Capacitor app, you can make your next awesome app using Capacitor Full App

Capacitor Full App with huge number of layouts and features

Capacitor Full App with huge number of layouts and features

More Ionic Angular Blogs

If you need a base to start your next Ionic 4 Angular app with Cordova, you can make your next awesome app using Ionic 4 Full App


Ionic 4 Full App with huge number of layouts and features
💖 💪 🙅 🚩
abhijeetrathor2
Abhijeet Rathore

Posted on March 29, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related