How to create a simple QRCode / barcode scanner app in iOS swift?

Let’s see how we can create a QRCode or barcode scanner app in iOS using swift AVFoundation.

It is easy to create a QRCode scanner app in iOS using swift. The AVFoundation framework provides a default implementation to do the same. Let us see how it is done.

AVFoundation has AVCaptureSession which provides the camera interface which is needed to scan the code. All that we have to do is to add a customized version of AVCaptureMetadataOutput to the AVCaptureSession instance and call startRunning() on the same.

AVCaptureMetadataOutput has a metadataObjectTypes array which should be customized based on our requirement and should conform to the AVCaptureMetadataOutputObjectsDelegate.

let metadataOutput = AVCaptureMetadataOutput()
metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
metadataOutput.metadataObjectTypes = [.qr, .ean8, .ean13, .pdf417]

When we start the session, it will continuously scan for the provided metadataObjectTypes and call the delegate method if any of the matching types are found. Then we can either call stopRunning() on the captureSession instance or continue scanning if you want.

func metadataOutput(_ output: AVCaptureMetadataOutput,
didOutput metadataObjects: [AVMetadataObject],
from connection: AVCaptureConnection) {
// do your work here...
}

I created a sample class which does all these work for you.

Here is a GitHub sample project to do the same.

Reference: Hackingwithswift.

That’s it. !

Enjoy!!

If you enjoyed reading this post, please share and give some claps so others can find it 👏👏👏👏👏 !!!!

You can follow me on Medium for fresh articles. Also, connect with me on LinkedIn.

If you have any comment, question, or recommendation, feel free to post them in the comment section below!