Building a Simple Barcode Scanner in iOS

9/27/2017 Updated for Xcode 9/Swift 4

Although near-field communication (NFC) technologies such as Apple Pay are beginning to gain traction as a means of inter-device communication, visual communication mechanisms such as barcodes (both 1D and 2D) are still widely used across a broad range of industries.

This tutorial demonstrates how to easily incorporate barcode scanning functionality into an iOS application. The sample application will use the AVFoundation framework to capture and analyze barcode images using the device's camera. iOS 10, macOS 10.12, and Xcode 8 are required.

Create the Xcode Project

The first step is to create the Xcode project we'll be using to build the example app.

  • Open Xcode and select File | New | Project from the menu.
  • In the project template dialog, select iOS > Single View Application and click "Next".
  • Name the product "BarcodeScanner" and fill in the remaining fields as appropriate for your team and organization. Ensure that Swift is selected as the development language and click "Next".
  • Save the project to an appropriate location on your system.

Although it doesn't actually do anything yet, you should now be able to run the application by selecting your device in the toolbar and clicking the "Run" button or by pressing Command-R. Note that, since the application will use the camera, it needs to be run on an actual device and must be signed. Make sure that an appropriate development team is selected in the Signing section of the General tab for the "BarcodeScanner" target before attempting to run the app.

Add the CameraView Class

Before we can display the camera preview to the user, we need to create a class to represent the camera view.

  • Select ViewController.swift in the Project Navigator.
  • Add the following line to the imports section:
    import AVFoundation
  • Add the following class declaration immediately before the ViewController class that was automatically generated by Xcode:
    class CameraView: UIView {
        override class var layerClass: AnyClass {
            get {
                return AVCaptureVideoPreviewLayer.self
            }
        }
    
        override var layer: AVCaptureVideoPreviewLayer {
            get {
                return super.layer as! AVCaptureVideoPreviewLayer
            }
        }
    }

This class extends UIView and overrides the layerClass property to specify that the view will be backed by an instance of AVCaptureVideoPreviewLayer. It also overrides the layer property to cast the return value to AVCaptureVideoPreviewLayer. This will make it easier to access the properties of the preview layer later.

Add the Camera View to the View Controller

Next, we'll add the camera view to the view controller.

  • In the ViewController class, declare a member variable to contain the camera view. Since we'll be creating the view instance programmatically, we don't need to tag it as an outlet:
    var cameraView: CameraView!
  • Override the loadView() method to initialize the view:
    override func loadView() {
        cameraView = CameraView()
    
        view = cameraView
    }

Although the camera view will now be visible when we run the app, it won't yet show anything but a black rectangle. We'll fix this in the next section.

Configure the Capture Session

In order to get the camera view to actually reflect what the camera is seeing, we need to connect it to an AV capture session. We'll use a dispatch queue to execute the more expensive session operations so the UI isn't blocked while waiting for them to complete.

  • Add member variables for the capture session and dispatch queue to ViewController:
    let session = AVCaptureSession()
    let sessionQueue = DispatchQueue(label: AVCaptureSession.self.description(), attributes: [], target: nil)
  • Add the AVCaptureMetadataOutputObjectsDelegate protocol to the view controller class:
    class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { 
        ...
    } 
  • Add the following code to viewDidLoad() to initialize the capture session. For this example, we'll be configuring the session to recognize two barcode types – EAN-13 (aka "UPC") codes and QR codes:
    session.beginConfiguration()
    
    let videoDevice = AVCaptureDevice.default(for: .video)
    
    if (videoDevice != nil) {
        let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice!)
    
        if (videoDeviceInput != nil) {
            if (session.canAddInput(videoDeviceInput!)) {
                session.addInput(videoDeviceInput!)
            }
        }
    
        let metadataOutput = AVCaptureMetadataOutput()
    
        if (session.canAddOutput(metadataOutput)) {
            session.addOutput(metadataOutput)
    
            metadataOutput.metadataObjectTypes = [
                .ean13,
                .qr
            ]
    
            metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        }
    }
    
    session.commitConfiguration()
    
    cameraView.layer.session = session
    cameraView.layer.videoGravity = .resizeAspectFill
  • Add the following additional code to viewDidLoad() to set the initial camera orientation:
    let videoOrientation: AVCaptureVideoOrientation
    switch UIApplication.shared.statusBarOrientation {
        case .portrait:
            videoOrientation = .portrait
    
        case .portraitUpsideDown:
            videoOrientation = .portraitUpsideDown
    
        case .landscapeLeft:
            videoOrientation = .landscapeLeft
    
        case .landscapeRight:
            videoOrientation = .landscapeRight
    
        default:
            videoOrientation = .portrait
    }
    
    cameraView.layer.connection?.videoOrientation = videoOrientation

Add Camera Usage Description to Info.plist

Use of the camera in an iOS application requires the user's permission. In order for iOS to ask for permission, we need to provide a string explaining what the application plans to do with the camera.

  • Add the camera usage description to Info.plist:
        <key>NSCameraUsageDescription</key>
        <string>to scan barcodes</string>

The application still doesn't do much, but it will now at least prompt the user for permission to access the camera:

Start and Stop the Capture Session

In order for the application to actually display what the camera is seeing, we need to start the capture session. We'll do this when the view appears. We'll also stop the session when the view disappears.

  • Add the following methods to ViewController to start and stop session capture:
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    
        sessionQueue.async {
            self.session.startRunning()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    
        sessionQueue.async {
            self.session.stopRunning()
        }
    }

While it isn't capable of scanning barcodes yet, the application will now at least correctly show the camera preview:

Handle Orientation Changes

Although it now displays the preview, the application doesn't yet respond to changes in orientation. Next, we'll add code to update the camera orientation when the device is rotated.

  • Add the following method to ViewController to update the preview orientation when the device orientation changes:
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
    
        // Update camera orientation
        let videoOrientation: AVCaptureVideoOrientation
        switch UIDevice.current.orientation {
            case .portrait:
                videoOrientation = .portrait
    
            case .portraitUpsideDown:
                videoOrientation = .portraitUpsideDown
    
            case .landscapeLeft:
                videoOrientation = .landscapeRight
    
            case .landscapeRight:
                videoOrientation = .landscapeLeft
    
            default:
                videoOrientation = .portrait
        }
    
        cameraView.layer.connection?.videoOrientation = videoOrientation
    }

Now, when the device is rotated, the preview will reflect the correct orientation.

Capture Barcode Values

Finally, we're ready to add the code that actually captures barcode values. We'll do this using the captureOutput(_:didOutputMetadataObjects:from:) method of the AVCaptureMetadataOutputObjectsDelegate protocol.

  • Add the following method to ViewController:
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        if (metadataObjects.count > 0 && metadataObjects.first is AVMetadataMachineReadableCodeObject) {
            let scan = metadataObjects.first as! AVMetadataMachineReadableCodeObject
    
            let alertController = UIAlertController(title: "Barcode Scanned", message: scan.stringValue, preferredStyle: .alert)
    
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler:nil))
    
            present(alertController, animated: true, completion: nil)
        }
    }

When a barcode is recognized, the application will now extract the associated value and present it to the user in an alert view:

Summary

This tutorial demonstrated how to easily incorporate barcode scanning functionality into an iOS application using the AVFoundation framework. For more ways to simplify iOS app development, please see my projects on GitHub:

  • MarkupKit – Declarative UI for iOS and tvOS
  • HTTP-RPC – Lightweight multi-platform REST

9 thoughts on “Building a Simple Barcode Scanner in iOS

  1. It doesnt recognize the last two(and 5) supplemental digits for EAN13 barcode types, any workarounds would be really helpful.

    Like

    1. Can you be more specific? The application was written in Swift 3, and I just compiled it using Swift 3.2 without any problem.

      Note that you need to run the application on an actual device. It does not work in the simulator.

      Like

  2. Using this and it works fine but having trouble adding a rectOfInterest to make it scan only a small region.

    Do you have sample code for that as well?

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s