BarcodeScanner with Ionic

I’m messing around with the new Ionic Framework. Ionic builds on top of Angular and builds using Cordova. Integrating a QR code scanner cannot be any simpler with the Cordova BarcodeScanner plugin in place.

But things are never as simple as they look … I run into funny issues on Android. Basically the problem is if a user cancels the barcode scanning process on Android using the back button, the application will simple quit itself, if I don’t do an alert() or something similar. It seems like the Android back button click was registered twice, first time in the QR scanner, and 2nd time in the main app. I had to write the following hacks to make sure it doesn’t quit my app.

First, qr_scan_service.js. Very straight forward service class wrapping the cordova plugin.

var app = angular.module('app.services');

app.factory('QRScanService', [function () {

  return {
    scan: function(success, fail) {
      cordova.plugins.barcodeScanner.scan(
        function (result) { success(result); },
        function (error) { fail(error); }
      );
    }
  };

}]);

Next, putting some voodoos in the calling controller code. See comments.

var app = angular.module('app.controllers');

app.controller('SomeCtrl',
               ['QRScanService', '$ionicPopup', '$ionicModal',
                function(QRScanService, $ionicPopup, $ionicModal) {

  this.scanIt = function() {
    QRScanService.scan(function(result) {
      if (result.cancelled) {
        // this is a super hack. When QR scan gets cancelled by
        // clicking the back button on android, the app quits...
        // doing a blank modal to catch the back button press event
        $ionicModal.fromTemplate('').show().then(function() {
          $ionicPopup.alert({
            title: 'QR Scan Cancelled',
            template: 'You cancelled it!'
          });
        });
      } else {
        $ionicPopup.alert({
          template: 'Result: ' + result.text
        });
      }
    }, function(error) {
      $ionicPopup.alert({
        title: 'Unable to scan the QR code',
        template: 'Too bad, something went wrong.'
      });
    });
  };

}]);
Published: 2014-05-29
blog comments powered by Disqus