Starting with iOS 7, Apple provides an underlying API for scanning in the AVFoundation library.
We’re not going to build a full featured application, but more like a starting point for that barcode scanning app you’ve been wanting to make.
This meager one hundred-ish lines of code will be able to scan both 1 and 2 dimensional barcodes and return the text version of the code.
All this magic happens by implementing the AVCaptureMetadataOutputObjectsDelegate
For this demo I’ll have the main view controller implement the AVCapture... delegate.
I’m going to show the complete code below, and then walk through it.
First we add an import for AVFoundation.
Next we make our view controller implement the delegate: AVCaptureMetadataOutputDelegate.
Next we need to setup some variables:
Inside our override for viewDidLoad we’ll add some code to handle the UIView that’ll be displayed once we have a successful scan.
Next we have the device, input and output setup. We set “device” to be the default device for video, which is your camera. The input is whatever your camera sees, a barcode if you’re doing it correctly. If you see your finger covering the lens, you’re probably doing it wrong...unless you have a barcode on your finger. The output is whatever capture is found when scanning. The output sets the current view controller as its delegate.
Now we need to be able to paint whatever your camera sees on the screen. We initialize the previewLayer variable from the top of the class passing in the session we created earlier.
The frame can be any size you like, I opted for full screen for this demo, so I set the frame to the view controller’s size. The gravity determines how the preview will be displayed inside your frame.
And then we add this preview to our view’s layer as a sublayer.
The last step here is to start the capture. We do that by calling:
Okay, we’re almost done, we need only to implement the method that is called on successful capture and we’ll have a working prototype.
The method signature should look like:
Here we have the implementation of the method. It starts out with a few variable declarations. We have a CGRect that’ll serve as the dimensions for the captured reticle, the barcode, the parsed string and the allowed barcode types. We loop over the metadataObjects that are passed into the method, and determine if the captured barcode is one of our allowed types. If so we parse the string value out set the capture reticle and stop the scanner. That’s all there is to it. Apple has made barcode scanning a simple matter as of iOS 7.
For this demo we only print the result to the console. I trust you’ll do something much more interesting; and when you do, drop us a line and tell us what you did with it. We love hearing about cool swift apps!
Download the demo project and try it out for yourself. Barcode Scanner Demo