Add Barcode Scanning Functionality To Your Ionic 2 App

Being able to scan a barcode is a convenient way to share bits of data.  Whether you’re using QR codes to share contact information or traditional barcodes for product information, being able to scan an image is more convenient than either entering a long code or similar.

Previously I wrote about scanning barcodes using Ionic Framework 1, but with Ionic 2 being all the rage I thought it would be worth revisiting for Angular 2.

In this guide we’re going to look at the PhoneGap BarcodeScanner plugin.  It is capable of scanning the following barcode types on Android:

  • QR_CODE
  • DATA_MATRIX
  • UPC_E
  • UPC_A
  • EAN_8
  • EAN_13
  • CODE_128
  • CODE_39
  • CODE_93
  • CODABAR
  • ITF
  • RSS14
  • PDF417
  • RSS_EXPANDED

And it can scan the following barcode types on iOS:

  • QR_CODE
  • DATA_MATRIX
  • UPC_E
  • UPC_A
  • EAN_8
  • EAN_13
  • CODE_128
  • CODE_39
  • ITF

That information was taken right out of the official documentation.  Now you’re probably thinking that this is a PhoneGap plugin so it won’t work for Ionic 2.  The reality is that PhoneGap based on Apache Cordova just like Ionic Framework, so they can all play nice together.

With the background out of the way, let’s start creating a project that can use this plugin.  From your Command Prompt (Windows) or Terminal (Mac and Linux), execute the following:

A few important things to note.  First, if you’re not using a Mac you cannot add and build for the iOS platform.  Second, you must be using the Ionic CLI that supports Ionic 2 applications.

From within your project, execute the following from your Command Prompt or Terminal:

This will install the barcode plugin for use in your project.

From here on out we can start coding.  We’ll spend most of our time in the app/pages/home/home.html and app/pages/home/home.js files.  One being our UI file and the other being our logic file.

Starting with app/pages/home/home.js, add the following code:

Let’s break down everything that is happening in the above.

In the constructor method we are passing and initializing our platform and navController objects.  Because we’ll be using a native plugin we need to make sure the device is ready first.  The Platform class has a function to check for us if the device is ready.

Inside the scan method we do that check and once ready we call the scan function of the actual barcode plugin.  If the promise is resolved we will show an alert with the scanned result.  If the promise was rejected we will show an alert with the error.

Now let’s take a look at the front end code.  We are trying to keep things simple which can easily be reflected in this file.  Open app/pages/home/home.html and include the following code:

We really only have a button that starts the scanner in our UI.  Very simple right?

Conclusion

Making use of the barcode scanner plugin in Ionic 2 really wasn’t too different from what was done in the Ionic Framework 1 tutorial I wrote.  This is because both versions of the framework use the same plugin.  The only difference was in the use of AngularJS and Angular 2.

Nic Raboy

Nic is a skilled application developer who has released several native and hybrid mobile applications to iTunes and Google Play. He writes about his development experiences related to making web and mobile app development easier to understand and has experience in Android, Node.js, Apache Cordova, Java, NoSQL, SQL, GoLang, NativeScript, and Unity3D.

  • sufiyan khan

    hi Nic,
    Any suggestions on ocr with ionic??

  • Gonzoide

    HI,

    Using latest Ionic CLI, when implementing your example in my own code I get an error message indicating that “cordova” is unknown, from line :

    cordova.plugins.barcodeScanner.scan((result) => {

    Is there something I am missing to make cordova known from my project ? Thanks.

    Your system information:

    Cordova CLI: 5.3.3
    Ionic Version: 2.0.0-beta.3
    Ionic CLI Version: 2.0.0-beta.19
    Ionic App Lib Version: 2.0.0-beta.9
    OS: Windows 8.1
    Node Version: v0.12.2

    • Can you share your full logs?

      • Gonzoide

        Sure. BTW, I forgot to mention I was developing in TypeScript.

        Globally speaking, I think the current official doc on Ionic 2 is a little bit lightweight (since of course we’re still in Beta) : if we consider the example of Barcode, methods are described but nothing about how to import and inject instances, so you get method names but can’t apply them 🙂

        There is also the ongoing issue of imports : sometimes to import an Ionic feature ‘ionic-framework/ionic’ should be used, sometimes ‘ionic/ionic’ (for the same feature), in my case most of the time none works (I am only at the beginning of migrating a full Ionic 1 app to Ionic 2 + TS)

        ./app/app.ts
        Module build failed: Error: Cannot resolve module ‘ionic/ionic’ in D:ionic2myappappservices
        Required in D:ionic2myappappservicesalert.ts
        at ResolutionError.Error (native)
        at new ResolutionError (D:ionic2myappnode_modulesawesome-typescript-loaderdist.babeldeps.js:482:88)
        at D:ionic2myappnode_modulesawesome-typescript-loaderdist.babeldeps.js:301:37
        at tryCatcher (D:ionic2myappnode_modulesawesome-typescript-loadernode_modulesbluebirdjsmainutil.js:26:23)
        at CatchFilter.doFilter (D:ionic2myappnode_modulesawesome-typescript-loadernode_modulesbluebirdjsmaincatch_filter.js:52:40)
        at CatchFilter.tryCatcher (D:ionic2myappnode_modulesawesome-typescript-loadernode_modulesbluebirdjsmainutil.js:26:23)
        at Promise._settlePromiseFromHandler (D:ionic2myappnode_modulesawesome-typescript-loadernode_modulesbluebirdjsmainpromise.js:507:31)
        at Promise._settlePromiseAt (D:ionic2myappnode_modulesawesome-typescript-loadernode_modulesbluebirdjsmainpromise.js:581:18)
        at Promise._settlePromises (D:ionic2myappnode_modulesawesome-typescript-loadernode_modulesbluebirdjsmainpromise.js:697:14)
        at Async._drainQueue (D:ionic2myappnode_modulesawesome-typescript-loadernode_modulesbluebirdjsmainasync.js:123:16)
        at Async._drainQueues (D:ionic2myappnode_modulesawesome-typescript-loadernode_modulesbluebirdjsmainasync.js:133:10)
        at Immediate.Async.drainQueues [as _onImmediate] (D:ionic2myappnode_modulesawesome-typescript-loadernode_modulesbluebirdjsmainasync.js:15:14)
        at processImmediate [as _immediateCallback] (timers.js:358:17)
        @ multi main,[default] D:/ionic2/myapp/app/services/alert.ts:2:46
        Cannot find module ‘ionic/ionic’.,[default] D:/ionic2/myapp/app/services/alert.ts:70:9
        Property ‘plugins’ does not exist on type ‘Window’.,[default] D:/ionic2/myapp/app/services/barcode.ts:7:8
        Cannot find name ‘BarcodeScanner’.,[default] D:/ionic2/myapp/app/services/event.ts:85:78
        Supplied parameters do not match any signature of call target.,[default] D:/ionic2/myapp/app/services/event.ts:89:80
        Supplied parameters do not match any signature of call target.,[default] D:/ionic2/myapp/app/services/social.ts:13:12
        Property ‘plugins’ does not exist on type ‘Window’.,[default] D:/ionic2/myapp/app/services/social.ts:14:23
        Property ‘plugins’ does not exist on type ‘Window’.,[default] D:/ionic2/myapp/app/services/social.ts:21:12
        Property ‘plugins’ does not exist on type ‘Window’.,[default] D:/ionic2/myapp/app/services/social.ts:22:23
        Property ‘plugins’ does not exist on type ‘Window’.,[default] D:/ionic2/myapp/app/services/social.ts:29:12
        Property ‘plugins’ does not exist on type ‘Window’.,[default] D:/ionic2/myapp/app/services/social.ts:30:23
        Property ‘plugins’ does not exist on type ‘Window’.,[default] D:/ionic2/myapp/app/services/url.ts:15:15
        Property ‘cordova’ does not exist on type ‘Window’. (CLI v2.0.0-beta.19)

        Your system information:

        Cordova CLI: 5.3.3
        Ionic Version: 2.0.0-beta.3
        Ionic CLI Version: 2.0.0-beta.19
        Ionic App Lib Version: 2.0.0-beta.9
        OS: Windows 8.1
        Node Version: v0.12.2

        • A few things:

          I just updated the code snippet because it changed slightly in the latest beta of Ionic 2.
          Nowhere in my code am I using the Barcode class of Ionic Native. I recommend using the core Apache Cordova plugins with vanilla JavaScript, not Ionic Native. At least for now.
          I am using JavaScript not TypeScript.

          That said, you should follow the tutorial the way I wrote it. Depending on how successful you are with what I wrote, we can go from there.

          Best,

          • Ryan Loggerythm

            Hi Nic,

            Great tutorial! Why do you suggest using Cordova’s scanner as opposed to the new Ionic Native version?

            Thanks,
            Ryan

          • Ionic Native is only a wrapper for Apache Cordova plugins. Since Ionic 2 is in beta, Ionic Native is subject to change at any given time. It is possible, but improbable that the vanilla plugin changes making it a smarter choice.

            Ionic Native is the next generation of ngCordova if you’re familiar with that. I personally find ngCordova to be a disaster so I am skeptical about the long term success of Ionic Native. I’m all about the safer approach ;-).

            Best,

        • forextor

          Hi Gonzoide, I had the same error using TypeScript… I got it to work by following this: http://www.joshmorony.com/using-cordova-plugins-in-ionic-2-with-ionic-native/ and http://ionicframework.com/docs/v2/native/Barcode%20Scanner/

  • Enming Chen

    Hi Nic,

    Thanks for your work, I learn a lot from your tutorials.

    In this section, there is a written mistake in home.js file, this.navController = navController should change to this.nav = navController.

  • Anderson Trujillo

    Hi Nic
    thanks for you work.
    but I try install the plugin ionic plugin add phonegap-plugin-barcodescanner, this is the error npm
    http GET http://registry.cordova.io/phonegap-plugin-barcodescanner

    npm
    http GET http://registry.cordova.io/phonegap-plugin-barcodescanner

    npm
    http GET http://registry.cordova.io/phonegap-plugin-barcodescanner

    Error: read ECONNRESET
    at exports._errnoException (util.js:1022:11)
    at TCP.onread (net.js:569:26)

    MacBook-Pro-de-Anderson:BarcodeProject andersontrujillor$

    This is in MAC, MY APLICATION IS FOR IOS