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

            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() {

    title = "Barcode Scanner"

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

        let metadataOutput = AVCaptureMetadataOutput()

        if (session.canAddOutput(metadataOutput)) {

            metadataOutput.metadataObjectTypes = [

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


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


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:
<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) {

    sessionQueue.async {

override func viewWillDisappear(_ animated: Bool) {

    sessionQueue.async {

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)


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:


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.