Как использовать плагин BarcodeScanner от NativeScript

Я только начал использовать NativeScript, и мне нужно уметь читать QR-коды. Я загрузил плагин BarcodeScanner для NativeScript (я использую JavaScript, а не TypeScript) и не могу понять, как его использовать. Я до сих пор не могу найти никаких полезных или информативных руководств. Кто-нибудь знает какие-нибудь хорошие учебники или может ли кто-нибудь сказать мне, как его использовать (с примером). Заранее спасибо!


person HittmanA    schedule 03.11.2016    source источник


Ответы (1)


Вы можете просмотреть репозиторий плагинов демонстрационный проект, где было показано, как используйте 1_. Что касается этого, проект был написан на TypeScript, однако вы можете клонировать репо и построить проект, а затем вы можете просмотреть скомпилированные файлы JavaScript. Для вашей помощи я прилагаю код JavaScript из демонстрации плагинов.

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;

Надеюсь это поможет

person Nikolay Tsonev    schedule 03.11.2016
comment
Большое спасибо! Вы спасли мой проект! - person HittmanA; 03.11.2016