无法在移动设备中读取条形码128

时间:2017-07-27 08:45:08

标签: ios swift3

我有一个用于通过手机摄像头读取条形码的代码,但它无法识别代码-128。任何人都知道代码有什么问题吗?

class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

var cameraView: CameraView!
let session = AVCaptureSession()
let sessionQueue = DispatchQueue(label: AVCaptureSession.self.description(), attributes: [], target: nil)

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

// *捕获初始化/配置会话以识别两种条形码类型*

        session.beginConfiguration()

    let videoDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

    if (videoDevice != nil) {
        let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice)

        if (videoDeviceInput != nil) {
            if (session.canAddInput(videoDeviceInput)) {
                session.addInput(videoDeviceInput)
            }
        }

        let metadataOutput = AVCaptureMetadataOutput()

        if (session.canAddOutput(metadataOutput)) {
            session.addOutput(metadataOutput)

            metadataOutput.metadataObjectTypes = [
                AVMetadataObjectTypeEAN13Code,
                AVMetadataObjectTypeQRCode
            ]

            metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        }
    }

    session.commitConfiguration()

    cameraView.layer.session = session
    cameraView.layer.videoGravity = AVLayerVideoGravityResizeAspectFill

结束视图控制器类

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
    if (metadataObjects.count > 0 && metadataObjects.first is AVMetadataMachineReadableCodeObject) {
        let scan = metadataObjects.first as! AVMetadataMachineReadableCodeObject

        let alertController = UIAlertController(title: "Barcode Scanned", message: scan.stringValue, preferredStyle: .alert)

        alertController.addAction(UIAlertAction(title: "OK", style: .default, handler:nil))

        present(alertController, animated: true, completion: nil)
    }
}

1 个答案:

答案 0 :(得分:0)

您正在配置相机以扫描 Ean13 QR 代码。你只需要替换这些行:

metadataOutput.metadataObjectTypes = [
            AVMetadataObjectTypeEAN13Code,
            AVMetadataObjectTypeQRCode
        ]

用这些:

metadataOutput.metadataObjectTypes = [
            AVMetadataObjectTypeCode128Code
        ]