我正在快速创建条形码扫描仪作为 NSObject
子类,但是无法触发
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!)
委托方法。这是我的 class 代码。
class CKScanner: NSObject, AVCaptureMetadataOutputObjectsDelegate {
//test
var delegate: AVCaptureMetadataOutputObjectsDelegate?
var frame: CGRect
//UPC Scan properties
let avSession:AVCaptureSession = AVCaptureSession()
let avDevice:AVCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var avInput:AVCaptureDeviceInput?
var avOutput:AVCaptureMetadataOutput?
var avPreviewLayer: AVCaptureVideoPreviewLayer?
var scannedUPC: NSString
{
get {
return self.scannedUPC
}
}
required init(_frame: CGRect, _parentView: CALayer) {
frame = _frame
super.init()
startScanning(_parentView)
}
func startScanning(_parentLayer: CALayer) {
println("started scanning")
var error: NSError?
avInput = AVCaptureDeviceInput(device: avDevice, error: &error)
if error != nil {
println("Error: \(error!.localizedDescription)")
return
}
if avSession.canAddInput(avInput!) {
avSession.addInput(avInput!)
}
avPreviewLayer = AVCaptureVideoPreviewLayer(session: avSession)
if avPreviewLayer != nil {
avPreviewLayer!.frame = frame
avPreviewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
_parentLayer.addSublayer(avPreviewLayer!)
}
avOutput = AVCaptureMetadataOutput()
avOutput!.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
if avSession.canAddOutput(avOutput!) {
avSession.addOutput(avOutput!)
avOutput!.metadataObjectTypes = avOutput!.availableMetadataObjectTypes
}
else {
println("cant add output")
}
avSession.startRunning()
}
//scanner was able to scan a barcode
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {}
在我的ViewController中,我打电话
var scanner = Scanner(frame: frame, _parentLayer: layer)
我也试图在我的ViewController中而不是在Scanner类中设置委托,但是没有运气。
是的,我确实在文件顶部添加了
AVCaptureMetadataOutputObjectsDelegate
以正确设置 scanner.delegate = self
。 最佳答案
如果您专门将metadataObjectTypes设置为
[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code]
有什么区别吗?