Barcode string value when using Vision Framework iOS11

The following Swift code snippet uses the new iOS11 Vision framework to parse an image and search for QR codes within it.

let barcodeRequest = VNDetectBarcodesRequest(completionHandler {(request, error) in
    for result in request.results! {
        if let barcode = result as? VNBarcodeObservation {                    
            if let desc = barcode.barcodeDescriptor as? CIQRCodeDescriptor {
                let content = String(data: desc.errorCorrectedPayload, encoding: .isoLatin1)
                print(content) //Prints garbage
            }
        }
    }
}
let image = //some image with QR code...
let handler = VNImageRequestHandler(cgImage: image, options: [.properties : ""])
try handler.perform([barcodeRequest])

      

The problem, however, is that it desc.errorCorrectedPayload

returns the raw encoded data as it was read from a QR code. To get the content string to print from the descriptor, you need to decode this raw data (for example, determine the mode from the first 4 bits).

This gets even more interesting since Apple already has the code to decode the raw data in AVFoundation. The class AVMetadataMachineReadableCodeObject

already has a field .stringValue

that returns the decoded string .

Is it possible to access this decoding code and use it also in the Vision framework?

+3


source to share


1 answer


It seems you can now get the decoded string from the barcode using the new payloadStringValue property VNBarcodeObservation

introduced in iOS 11 beta 5.



if let payload = barcodeObservation.payloadStringValue {
    print("payload is \(payload)")
}

      

+3


source







All Articles