Search code examples
swiftuiimageqr-code

How can you scan a UIImage for a QR code using Swift


I'm trying to read a QR code from a static image using Swift.

I can easily read it using a video source although it seems to be very different for images and I can't find too many resources online for this.

Any help appreciated, thanks.


Solution

  • func readQRCode(from image: UIImage) -> Result<String, QRReadingError> {
        guard let ciImage = CIImage(image: image) else {
            print("Couldn't create CIImage")
            return .failure(.generic)
        }
    
        guard let detector = CIDetector(
            ofType: CIDetectorTypeQRCode,
            context: nil,
            options: [CIDetectorAccuracy: CIDetectorAccuracyHigh]
        ) else {
            print("Detector not intialized")
            return .failure(.generic)
        }
        let features = detector.features(in: ciImage)
        let qrCodeFeatures = features.compactMap { $0 as? CIQRCodeFeature }
        guard let qrCode = qrCodeFeatures.first?.messageString else {
            print("No QR code found in the image")
            return .failure(.qrCodeNotFoundInImage)
        }
        return .success(qrCode)
    }
    
    enum QRReadingError: Error {
        case generic
        case qrCodeNotFoundInImage
    }