HittmanA
HittmanA

Reputation: 179

How to use BarcodeScanner plugin from NativeScript

I just started using NativeScript and need to be able to read QR codes. I downloaded the BarcodeScanner plugin for NativeScript (I am using JavaScript, not TypeScript) and I can't figure out how to use it. I still can not find any useful or informative tutorials. Does anyone know any good tutorials or can anyone tell me how to use it (with an example). Thanks in advance!

Upvotes: 1

Views: 4327

Answers (1)

Nikolay Tsonev
Nikolay Tsonev

Reputation: 1919

You could review plugins repo demo project, where has been shown how to use nativescript-barcodescanner. Regarding to the that, the project has been written on TypeScript, however you could clone the repo and build the project, then you could review the compiled JavaScript files. For your help I am attaching the JavaScript code from the plugins demo.

main-page.xml

<Page xmlns="http://www.nativescript.org/tns.xsd" xmlns:Barcode="nativescript-barcodescanner"  loaded="pageLoaded">
  <TabView class="tab-view">
    <TabView.items>
      <TabViewItem title="About">
        <TabViewItem.view>
          <StackLayout class="tab-content">
            <Image margin="10" src="~/res/telerik-logo.png" />
            <Label class="h3" text="BarcodeScanner plugin demo" />
            <Label class="body" text="The BarcodeScanner plugin supports extracting data from a large range of barcodes, including QR codes. Your app will receive the type of barcode and the encode value." textWrap="true"/>
          </StackLayout>
        </TabViewItem.view>
      </TabViewItem>
      <TabViewItem title="Demo">
        <TabViewItem.view>
          <ScrollView>
            <StackLayout class="tab-content">
              <Label class="h3" text="Checking availability" />
              <Label class="body" text="It can never hurt to check upfront if a device is capable of scanning a barcode." textWrap="true"/>
                  <Button class="btn btn-primary btn-rounded-sm" text="available?" tap="{{ doCheckAvailable }}" />

              <Label class="h3" text="Camera permission" />
              <Label class="body" text="Android 6+ and iOS 10+ require runtime user consent. The plugin handles it automatically but you can do it manually as well." textWrap="true"/>
              <Button class="btn btn-outline btn-rounded-sm" text="has permission?" tap="{{ doCheckHasCameraPermission }}" />
              <Button class="btn btn-primary btn-rounded-sm" text="request permission" tap="{{ doRequestCameraPermission }}" />

              <!--iOS>
                <ContentView height="240" width="240">
                  <Barcode:BarcodeScannerView></Barcode:BarcodeScannerView>
                </ContentView>
              </iOS-->

              <Label class="h3" text="Scanning (QR & EAN-13)" />
              <Label class="body" text="You can use the volume buttons to toggle the torch." textWrap="true"/>

                  <Button class="btn btn-primary btn-rounded-sm" text="back camera, with flip" tap="{{ doScanWithBackCamera }}" />
                  <Button class="btn btn-primary btn-rounded-sm" text="front camera, no flip" tap="{{ doScanWithFrontCamera }}" />
              <iOS>
                    <Button class="btn btn-primary btn-rounded-sm" text="back camera, with torch" tap="{{ doScanWithTorch }}" />
              </iOS>

              <Label class="h3" text="Continuous scanning (see console)" />
                  <Button class="btn btn-primary btn-rounded-sm" text="stop after 3 results" tap="{{ doContinuousScanMax3 }}" />
                  <Button class="btn btn-primary btn-rounded-sm" text="scan till you drop" tap="{{ doContinuousScan }}" />

              <Android>
                <Label class="h3" text="Orientation lock" />
                <Button class="btn btn-primary btn-rounded-sm" text="back camera, portrait" tap="{{ doScanPortrait }}" />
                <Button class="btn btn-primary btn-rounded-sm" text="back camera, landscape" tap="{{ doScanLandscape }}" />
              </Android>
            </StackLayout>
          </ScrollView>
        </TabViewItem.view>
      </TabViewItem>
    </TabView.items>
  </TabView>
</Page>

main-page.js

var main_view_model_1 = require("./main-view-model");
// Event handler for Page "loaded" event attached in main-page.xml
function pageLoaded(args) {
    // Get the event sender
    var page = args.object;
    page.bindingContext = new main_view_model_1.HelloWorldModel();
}
exports.pageLoaded = pageLoaded;

main-view-model.js

var observable_1 = require("data/observable");
var dialogs_1 = require("ui/dialogs");
var nativescript_barcodescanner_1 = require("nativescript-barcodescanner");
var HelloWorldModel = (function (_super) {
    __extends(HelloWorldModel, _super);
    function HelloWorldModel() {
        _super.call(this);
        this.barcodeScanner = new nativescript_barcodescanner_1.BarcodeScanner();
    }
    HelloWorldModel.prototype.doCheckAvailable = function () {
        this.barcodeScanner.available().then(function (avail) {
            dialogs_1.alert({
                title: "Scanning available?",
                message: avail ? "YES" : "NO",
                okButtonText: "OK"
            });
        }, function (err) {
            dialogs_1.alert(err);
        });
    };
    HelloWorldModel.prototype.doCheckHasCameraPermission = function () {
        this.barcodeScanner.hasCameraPermission().then(function (permitted) {
            dialogs_1.alert({
                title: "Has Camera permission?",
                message: permitted ? "YES" : "NO",
                okButtonText: "OK"
            });
        }, function (err) {
            dialogs_1.alert(err);
        });
    };
    HelloWorldModel.prototype.doRequestCameraPermission = function () {
        this.barcodeScanner.requestCameraPermission().then(function () {
            console.log("Camera permission requested");
        });
    };
    ;
    HelloWorldModel.prototype.doScanWithBackCamera = function () {
        this.scan(false, true);
    };
    ;
    HelloWorldModel.prototype.doScanWithFrontCamera = function () {
        this.scan(true, false);
    };
    ;
    HelloWorldModel.prototype.doScanWithTorch = function () {
        this.scan(false, true, true, "portrait");
    };
    ;
    HelloWorldModel.prototype.doScanPortrait = function () {
        this.scan(false, true, false, "portrait");
    };
    ;
    HelloWorldModel.prototype.doScanLandscape = function () {
        this.scan(false, true, false, "landscape");
    };
    ;
    HelloWorldModel.prototype.doContinuousScan = function () {
        this.barcodeScanner.scan({
            continuousScanCallback: function (result) {
                console.log(result.format + ": " + result.text);
            }
        });
    };
    ;
    HelloWorldModel.prototype.doContinuousScanMax3 = function () {
        var count = 0;
        console.log("-- in doContinuousScanMax3, count: " + count);
        var self = this;
        this.barcodeScanner.scan({
            reportDuplicates: false,
            continuousScanCallback: function (result) {
                count++;
                console.log(result.format + ": " + result.text + " (count: " + count + ")");
                if (count === 3) {
                    // funilly this is required on Android to reset the counter for a second run
                    count = 0;
                    self.barcodeScanner.stop();
                    setTimeout(function () {
                        dialogs_1.alert({
                            title: "Scanned 3 codes",
                            message: "Check the log for the results",
                            okButtonText: "Sweet!"
                        });
                    }, 1000);
                }
            }
        });
    };
    ;
    HelloWorldModel.prototype.scan = function (front, flip, torch, orientation) {
        this.barcodeScanner.scan({
            formats: "QR_CODE, EAN_13",
            cancelLabel: "EXIT. Also, try the volume buttons!",
            message: "Use the volume buttons for extra light",
            preferFrontCamera: front,
            showFlipCameraButton: flip,
            showTorchButton: torch,
            orientation: orientation,
            openSettingsIfPermissionWasPreviouslyDenied: true // On iOS you can send the user to the settings app if access was previously denied
        }).then(function (result) {
            // Note that this Promise is never invoked when a 'continuousScanCallback' function is provided
            setTimeout(function () {
                dialogs_1.alert({
                    title: "Scan result",
                    message: "Format: " + result.format + ",\nValue: " + result.text,
                    okButtonText: "OK"
                });
            }, 500);
        }, function (errorMessage) {
            console.log("No scan. " + errorMessage);
        });
    };
    ;
    return HelloWorldModel;
}(observable_1.Observable));
exports.HelloWorldModel = HelloWorldModel;

Hope this helps

Upvotes: 2

Related Questions