How to get decoded value from 1-D Barcode image (Swift)

decoded value from 1-D Barcode image (Swift)

For “CIDetector”, there is no way to read a 1 dimensional barcode. 1-D barcodes are not QR codes. Thus you can not use “CIDetectorTypeQRCode”.

1-D barcode images can be read using Apple Vision Api.

Below code is quite workable to get decoded value both from QR and Barcode images without using a third party library.

class Utility {
    
    private static var barcodeText = ""
    
    private static let barcodeRequest = VNDetectBarcodesRequest { (request, error) in
        guard let results = request.results else { return }
        for result in results {
            if let barcode = result as? VNBarcodeObservation {
                    if let text = barcode.payloadStringValue {
                    barcodeText = text
                }
            }
        }
    }

class func scanCodeFromImage(image: UIImage) -> String? {
        guard let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy : CIDetectorAccuracyHigh]), let ciImage = CIImage(image: image), let features = detector.features(in: ciImage) as? [CIQRCodeFeature] else { return nil }
        defer {
            Utility.barcodeText = ""
        }
        var qrCodeText = ""
        guard features.count > 0 else {
            if let cgImage = image.cgImage {
                let handler = VNImageRequestHandler.init(cgImage: cgImage, options: [:])
                do {
                    try handler.perform([barcodeRequest])
                } catch let error {
                    print("Error: Barcode image: ", error.localizedDescription)
                }
                qrCodeText = Utility.barcodeText
                return qrCodeText
            }
            return qrCodeText
        }
        for feature in features {
            if let message = feature.messageString {
                qrCodeText += message
            }
        }
        return qrCodeText
    }
}

Add above class in your project and just call below line from any class and get decoded value from QR or Barcode image.

guard let text = Utility.scanCodeFromImage(image: image), text != "" else {    
                return }

See the Stackoverflow

https://stackoverflow.com/questions/57265471/how-to-decode-from-1d-barcode-image