Search code examples
swiftqr-codeerror-correction

Is it possible to read a QR code's error correction value from iOS?


All QR codes define an error correction level, defined by two 'bits/pixels' in the lower-left (see here for more details.) While I know how to scan QR codes in Swift, what I don't know is how to get what the error correction is for the code I'm scanning.

This is needed because our app is trying to scan, then recreate the scanned QR code programmatically.

Here's our current code where we are notified of a successful QR code scan, but I don't see any way to get the QR-specific details, only the results of a successful scan...

extension QRCodeScannerViewController : AVCaptureMetadataOutputObjectsDelegate {

    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {

        guard let metadataObject = metadataObjects.first,
              let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject,
              let stringValue = readableObject.stringValue else {
            return
        }

        captureSession.stopRunning()

        performSegue(withIdentifier: "ShowResults", sender: stringValue)
    }
}

Looking through the docs I also see CIQRCodeDescriptor (https://developer.apple.com/documentation/coreimage/ciqrcodedescriptor) that does have the value we're looking for, but I'm not sure how to get an instance to inspect.


Solution

  • Duh! It was right in front of me!

    if let qrCodeDescriptor = readableObject.descriptor as? CIQRCodeDescriptor{
    
        switch qrCodeDescriptor.errorCorrectionLevel {
            case .levelL : print("L")
            case .levelM : print("M")
            case .levelH : print("H")
            case .levelQ : print("Q")
        }
    }