我尝试使用angular实现NativeScript中的条形码扫描程序。 我能够显示视频图层,但不幸的是我被困在处理条形码扫描事件。
我认为主要的问题是setMetadataObjectsDelegateQueue没有按预期工作。这意味着在函数captureOutputDidOutputMetadataObjectsFromConnection永远不会被调用。
在我的template.html中,我得到了一个占位符,它将被creationView模板替换。
我是在正确的轨道还是我错过了什么。不幸的是,我无法使用nativescript-barcodescanner插件,因为我想在现有布局中显示扫描仪。
import { Component, OnInit } from "@angular/core";
import {ios} from "application";
class BarcodeDelegate implements AVCaptureMetadataOutputObjectsDelegate {
captureOutputDidOutputMetadataObjectsFromConnection(captureOutput: AVCaptureOutput, metadataObjects: NSArray<any>, connection: AVCaptureConnection) {
console.log('test');
}
}
@Component({
selector: "ns-s",
moduleId: module.id,
templateUrl: "./test.component.html",
})
export class TestComponent implements OnInit {
public init: boolean = false;
public device: AVCaptureDevice;
ngOnInit() {
this.init = true;
}
creatingView(args) {
let session = new AVCaptureSession();
session.sessionPreset = AVCaptureSessionPreset1280x720;
// Adding capture device
this.device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo);
let input = AVCaptureDeviceInput.deviceInputWithDeviceError(this.device, null);
if (!input) {
throw new Error("Error trying to open camera.");
}
session.addInput(input);
// Layer for outputing AV Stuff
let videoLayer = AVCaptureVideoPreviewLayer.layerWithSession(session);
videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
let metadataOutput = new AVCaptureMetadataOutput();
if (session.canAddOutput(metadataOutput)) {
session.addOutput(metadataOutput);
try {
let delegate = new BarcodeDelegate();
// mainQueue var is to get dispatch_get_main_queue
let mainQueue = (function() {
let runloop = CFRunLoopGetMain();
return function(func) {
CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, func);
CFRunLoopWakeUp(runloop);
}
}());
metadataOutput.setMetadataObjectsDelegateQueue(delegate, mainQueue);
metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypePDF417Code
];
} catch(e) {
console.log(e);
}
} else {
console.log('error')
}
session.startRunning();
let view = UIView.alloc().initWithFrame({ origin: { x: 0, y: 0 }, size: { width: 400, height: 200 } });
videoLayer.frame = view.bounds;
view.layer.addSublayer(videoLayer);
args.view = view;
}
}