条形码扫描器作为NSObject子类

时间:2014-10-06 18:59:37

标签: ios swift

我在swift中创建条形码扫描程序作为 NSObject 子类,但是我无法解决

func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!)

委托方法。这是我的班级代码。

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

1 个答案:

答案 0 :(得分:0)

如果将metadataObjectTypes专门设置为

,该怎么办?
[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code]

有什么不同吗?