Building a Simple Barcode Scanner in iOS

11/13/2018 Updated for Xcode 10/Swift 4.2

Although near-field communication (NFC) technologies such as Apple Pay are continuing to gain traction as a means of inter-device communication, optical 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.

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 a 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
        }
    }

    func updateOrientation() {
        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
        }

        layer.connection?.videoOrientation = videoOrientation
    }
}

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

Finally, the class declares an updateOrientation() method that synchronizes the video orientation of the layer's capture connection with the device orientation. This method will be called by the view controller to initialize the view and to update it when the device orientation changes.

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: "Session Queue")
  • Add the AVCaptureMetadataOutputObjectsDelegate protocol to the view controller class:
class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
    ...
} 
  • Update the viewDidLoad() method to initialize the capture session and initialize the camera orientation:
override func viewDidLoad() {
    super.viewDidLoad()

    title = "Barcode Scanner"
    
    session.beginConfiguration()

    if let videoDevice = AVCaptureDevice.default(for: .video) {
        if let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice),
            session.canAddInput(videoDeviceInput) {
            session.addInput(videoDeviceInput)
        }

        let metadataOutput = AVCaptureMetadataOutput()

        if (session.canAddOutput(metadataOutput)) {
            session.addOutput(metadataOutput)

            metadataOutput.metadataObjectTypes = [
                .code128,
                .code39,
                .code93,
                .ean13,
                .ean8,
                .qr,
                .upce
            ]

            metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        }
    }

    session.commitConfiguration()

    cameraView.layer.session = session
    cameraView.layer.videoGravity = .resizeAspectFill

    cameraView.updateOrientation()
}

Add Camera Usage Description to Info.plist

Access to 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)

    cameraView.updateOrientation()
}

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 metadataOutput(_:didOutput:from:) method of the AVCaptureMetadataOutputObjectsDelegate protocol:

  • First, add the following property to ViewController:
var isShowingAlert = false
  • Next, add this method:
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
    if !isShowingAlert,
        metadataObjects.count > 0,
        metadataObjects.first is AVMetadataMachineReadableCodeObject,
        let scan = metadataObjects.first as? AVMetadataMachineReadableCodeObject {
        let alertController = UIAlertController(title: "Barcode Scanned", message: scan.stringValue, preferredStyle: .alert)

        isShowingAlert = true

        alertController.addAction(UIAlertAction(title: "OK", style: .default) { action in
            self.isShowingAlert = false
        })

        present(alertController, animated: true)
    }
}

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 incorporate barcode scanning functionality into an iOS application using the AVFoundation framework. Complete source code for this example can be found here.

Displaying an Activity Indicator while Loading Table View Data in the Background

11/13/2018 Updated for Xcode 10/Swift 4.2

iOS applications often need to retrieve data from a remote source such as a web service. This data is commonly loaded in the background to avoid blocking the main UI thread, causing the application to appear unresponsive.

While the data is being loaded, an application typically displays an activity indicator view to inform the user that something is happening. Often, this is done by dynamically adding an instance of UIActivityIndicatorView as a subview of either the current view or one of the view's ancestors and making the indicator active. However, if the view is a table or collection view, there is another option: the activity indicator can be set as the view's background view and shown or hidden as needed.

For example, the following code snippet shows a partial implementation of a simple table view controller. The table's data is provided by an array of strings stored in the rows property. The activity indicator is created and assigned as the table’s background view in loadView():

class ViewController: UITableViewController {
    var activityIndicatorView: UIActivityIndicatorView!
    
    var rows: [String]?
    
    let dispatchQueue = DispatchQueue(label: "Example Queue")
    
    override func loadView() {
        super.loadView()
    
        activityIndicatorView = UIActivityIndicatorView(style: .gray)
    
        tableView.backgroundView = activityIndicatorView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        title = "Activity Indicator"
    }
    
    ...
}

The data is "loaded" in viewWillAppear(). The controller simulates a web service call by sleeping for three seconds in the background, then populating the rows array and reloading the table data on the main thread. The activity indicator is shown while the background operation is executing, and is hidden when the operation is complete. Because table views in the default "plain" style show separator lines even when the table is empty, the controller also sets the table view's separator style to .none so the lines don't interfere with the activity indicator when it is visible:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if (rows == nil) {
        activityIndicatorView.startAnimating()

        tableView.separatorStyle = .none

        dispatchQueue.async {
            Thread.sleep(forTimeInterval: 3)

            OperationQueue.main.addOperation() {
                self.rows = ["One", "Two", "Three", "Four", "Five"]

                self.activityIndicatorView.stopAnimating()

                self.tableView.separatorStyle = .singleLine
                self.tableView.reloadData()
            }
        }
    }
}

Finally, the controller overrides the numberOfSections(in:), tableView(_:numberOfRowsInSection:), and tableView(_:cellForRowAt:) methods to provide the table content:

override func numberOfSections(in tableView: UITableView) -> Int {
    return (rows == nil) ? 0 : 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return rows?.count ?? 0
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifier = "cell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) ?? UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)

    cell.textLabel?.text = rows?[indexPath.row]

    return cell
}

The complete source code for this example can be found here.

How KVC Converts Strings to Numeric Types

Thanks to this discussion on Stack Overflow, I now understand how KVC is able to automatically convert string values to numeric types. As documented by Apple:

…setters like setValue:forKey: determine the data type required by a property’s accessor or instance variable, given a particular key. If the data type is not an object, the setter first sends an appropriate <type>Value message to the incoming value object to extract the underlying data, and stores that instead.

For example, if the type of the property being set is int:

@property int index;

KVC will attempt to invoke the intValue method on the provided value to convert it to the appropriate type before setting the property value:

[self setValue:@"10" forKey:@"index"]; // calls intValue on "10"

Thanks very much to Stack Overflow user CRD for providing the answer!