Home > other >  Barcode scanner doesnt work with codes generated by the app itself
Barcode scanner doesnt work with codes generated by the app itself

Time:12-02

This is how I simply generate Barcode:

extension UIImage
    convenience init?(text: String?, codeType: CodeType) {
        let isQRCode = codeType.isQrcode
        let data = text?.data(using: isQRCode ? .utf8 : .ascii)
        let filter = CIFilter(name: isQRCode ? "CIQRCodeGenerator" : "CICode128BarcodeGenerator")
        filter?.setValue(data, forKey: "inputMessage")
        if isQRCode {
            filter?.setValue("Q", forKey: "inputCorrectionLevel")
        }
        guard let ciimage = filter?.outputImage else {
            return nil
        }
        self.init(ciImage: ciimage.transformed(by: CGAffineTransform(scaleX: 12, y: 12)))
    }

An example usage is:

let image = UIImage(text: "hello stack overflow", type: .barcode)

The output is:

enter image description here

Now I have defined scanner like this:

private let session = AVCaptureSession()
private let output = AVCaptureMetadataOutput()

func setupSession(with delegate: AVCaptureMetadataOutputObjectsDelegate) {
    session.beginConfiguration()
    guard let device = AVCaptureDevice.default(for: .video), let input = try? AVCaptureDeviceInput(device: device),
          session.canAddInput(input), session.canAddOutput(output) else {
        return
    }
    session.addInput(input)
    session.addOutput(output)
    session.commitConfiguration()
    output.setMetadataObjectsDelegate(delegate, queue: queue)
    output.metadataObjectTypes = [.qr, .ean8, .ean13]
}

My delegate is the following:

func metadataOutput(
    _: AVCaptureMetadataOutput,
    didOutput metadataObjects: [AVMetadataObject],
    from _: AVCaptureConnection
) {
    print("*****")
    print(metadataObjects.first)
}

Of course nothing is printed here. Why? ‼️

When I scan any barcode from the google, for example:

enter image description here

then the output is correct:

*****
Optional(<AVMetadataMachineReadableCodeObject: 0x280efece0, type="org.gs1.EAN-13", bounds={ 0.5,0.3 0.0x0.4 }>corners { 0.5,0.7 0.5,0.7 0.5,0.3 0.5,0.3 }, time 556773637541541, stringValue "1234567890128")

CodePudding user response:

On your code, you generate a code-128 bar code, so you need a scanner capable of reading code-128 too.

You need to add code128 on the list of object type you want to read :

output.metadataObjectTypes = [.qr, .ean8, .ean13, .code128]
  • Related