SwiftUI: Image with barcode doesn't show up

Viewed 458

I'm trying to present an instance of UIImage, generated as a barcode from a string:

if let image = UIImage(barcode: "1234567890") {
    Image(uiImage: image)
}

But it shows empty rectangle, though in debug the image is populated with the real image:

enter image description here

I use a simple UIImage extension to generate an UIImage with barcode from a string:

extension UIImage {

    convenience init?(barcode: String) {
        let data = barcode.data(using: .ascii)
        guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else {
            return nil
        }

        filter.setValue(data, forKey: "inputMessage")
        guard let ciImage = filter.outputImage else {
            return nil
        }

        self.init(ciImage: ciImage)
    }

}

What's wrong? Any ideas?

1 Answers

Yes, looks like some defect/incompatibility with Image. You can file a feedback to Apple.

Meanwhile here is a workaround. Tested with Xcode 12 / iOS 14

demo

struct TestBarCodeView: View {
    var body: some View {
        VStack {
            BarCodeView(barcode: "1234567890")
                .scaledToFit()
                .padding().border(Color.red)
        }
    }
}

struct BarCodeView: UIViewRepresentable {
    let barcode: String
    func makeUIView(context: Context) -> UIImageView {
        UIImageView()
    }

    func updateUIView(_ uiView: UIImageView, context: Context) {
        uiView.image = UIImage(barcode: barcode)
    }
}
Related