Using QR/Barcodes with Swift

Keeping your code safe from COVID.

Bruno Muniz
ITNEXT

--

In this pandemic you have probably seen many restaurants using QR codes for their menu in order to avoid using carton-made menu that could possibly be contaminated by other customers. Today I’ll quickly go through how to use QR (quick-response) codes and even regular barcodes in Swift.

Photo by david pl on Unsplash

How do we create QR codes or barcodes?

To generate QR codes or barcodes we need CoreImage framework which is used to generate images and apply filters but we will be fine by just importing UIKit instead.

A weird thing about using CoreImage filters is that they are initialized with a string from the generator protocol you want to use. Here’s an official list of the generator protocols from the Apple docs.

You’ll notice that I force-unwrapped some things up here — In fact you could just use optionals, guard let, etc. I actually looked around if we could use a kCIIAttribute instead of inputMessage but I didn’t find anything. Let me know in the comments section if you know a workaround to not use Strings here. Besides of the not-so-cool strings for the CIFilter and the key the only thing we did was to scale the ciImage generated to be a bit more visible once you assign it to an UIImageView.

When generating a barcode, it is almost the exact same snippet but the CIFilter name will be CICode128BarcodeGenerator

How do we read a QR code or a barcode?

When we want to read a QR code or a barcode we need to set an incoming data stream: A capture session.

We’ll use AVCaptureVideoPreviewLayer to see what we are scanning. It will be initialized with the capture session and that’s why I used lazy init.

On viewDidLoad we setup the session with the device camera as input and with the output. In the output we can set what we’re looking for at metadataObjectTypes . After we set the metadata objects delegate, we will be able to implement metadataOutput(output:didOutput:fromConnection) which will provide us the detected metadata we chose.

To detect barcodes instead — same process. But instead of .qr as metadataObjectTypes, use .code128

--

--