MVVM in iOS

MVVM ("model/view/view-model") is design pattern that helps promote a separation of concerns in software development. It is an extension of the well-known "model/view/controller" (MVC) pattern that is often used in user interface design.

In a traditional MVC application, a "controller" object is used to mediate interaction between two other objects known as the "model" and the "view". The model is an abstract representation of data managed by the application, and the view is a visual representation of the data contained in the model. The controller notifies the view of changes to the model, and updates the model in response to user input events received from the view.

MVVM expands on MVC by further decoupling the view from the controller. Instead of requiring the controller to explicitly manage the view's state, a view in an MVVM application uses data binding to be automatically updated in response to changes in a "view model" object exposed by the controller. This object adapts the data provided by the underlying model so that it can be easily consumed by the view. The additional level of indirection allows the view and controller to vary independently without the risk of breaking one or the other.

MVC Example

For example, consider a simple custom table view cell implemented using MVC:

The cell class might provide a set of outlets that the table view controller can use to update its state:

class CustomCell: UITableViewCell {
    @IBOutlet var headingLabel: UILabel!
    @IBOutlet var detailLabel: UILabel!

    ...
}

The controller would use the outlets to populate the cell's contents when a new cell is requested. In this example, row data is provided by dictionary instances containing "heading" and "detail" values for each cell:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let row = rows[indexPath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! CustomCell

    cell.headingLabel.text = row["heading"] as? String
    cell.detailLabel.text = row["detail"] as? String

    return cell
}

However, this design creates a tight coupling between the controller and the custom cell view. Any time the view class changes, the controller must also be updated.

MVVM Example

MVVM solves this problem by decoupling the view from the controller. Rather than exposing its implementation details via outlets, the view registers itself as an observer on the properties of the view model. Using this approach, the view and controller both become dependent on the view model, but neither is dependent on the other. As long as the view model doesn't change, either one can be modified without impact.

For example, the following markup shows a custom table view cell implemented using MarkupKit, an open-source framework for building native iOS and tvOS applications using a simple, HTML-like markup language. The cell contains two labels arranged vertically in a column:

<LMColumnView>
    <UILabel class="label.heading" text="$content.heading"/>
    <UILabel class="label.detail" text="$content.detail"/>
</LMColumnView>

Instead of outlets, the custom cell class exposes a content property representing the view model. The labels' text properties are bound to the properties of this object:

class CustomCell: LMTableViewCell {
    // View model
    dynamic var content: [String: AnyObject]?

    ...
}

With the bindings established, the controller can be implemented as shown below. It simply dequeues a cell and sets its content property to the dictionary for the corresponding row. Because they are bound to the properties of the view model, the cell's labels are automatically updated to reflect the new values. No direct manipulation of view elements is required:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! CustomCell

    cell.content = rows[indexPath.row]

    return cell
}

Summary

This article introduced the MVVM design pattern and provided an example of how it can be used to simplify the implementation of a custom table view cell. A complete example can be found here.

For more information, see the MarkupKit README.

MarkupKit 3.0 Released

MarkupKit 3.0 is now available for download. The primary focus of this release was not the addition of new features but improvements to an existing feature.

In earlier versions, custom table and picker view data sources and delegates could call back into the source view to obtain information about static content. However, this approach relied on overrides of UIKit view methods such as numberOfSections, numberOfRowsInSection:, and cellForRowAtIndexPath:, which already have established and documented semantics. The redefined behavior did not always reflect the original intent, which could (and did) lead to bugs.

As of MarkupKit 3.0, a custom data source or delegate can call directly into the respective protocol implementations provided by LMTableView and LMPickerView. The view methods are no longer overridden, allowing them to retain their original behaviors.

However, while this approach provides a much cleaner and more deterministic delegation model, it is not backwards-compatible. All custom data source and delegate implementations must be updated to call the delegate methods instead of the view methods. Specifically, table view controllers that provide custom content should now extend the new LMTableViewController class and delegate to the base method as needed. For example:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let n: Int
    if (tableView.name(forSection: section) == "dynamic") {
        n = ...
    } else {
        n = super.tableView(tableView, numberOfRowsInSection: section)
    }

    return n
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: UITableViewCell
    if (tableView.name(forSection: indexPath.section) == "dynamic") {
        cell = ...
    } else {
        cell = super.tableView(tableView, cellForRowAt: indexPath)
    }

    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if (tableView.name(forSection: indexPath.section) == "dynamic") {
        ...
    } else {
        super.tableView(tableView, didSelectRowAt: indexPath)
    }
}

Additionally, controllers that provide custom content for LMPickerView instances should be updated to delegate to the picker view as shown below:

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return pickerView.numberOfComponents(in: pickerView)
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    let n: Int
    if (pickerView.name(forComponent: component) == "dynamic") {
        n = ...
    } else {
        n = pickerView.pickerView(pickerView, numberOfRowsInComponent: component)
    }

    return n
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    let title: String
    if (pickerView.name(forComponent: component) == "dynamic") {
        title = ...
    } else {
        title = pickerView.title(forRow: row, forComponent:component)!
    }

    return title
}

For more information, see the following examples or the project README:

MarkupKit 2.8 Released

MarkupKit 2.8 is now available for download. This release adds support for declarative data binding, facilitating development of MVVM-style applications using MarkupKit.

Using data binding, developers can eliminate a lot of the tedious boilerplate code that is typically required to manage the state of user interface elements explicitly. For example, the following markup binds the text property of a text field to the name property of the document’s owner:

<UITextField text="$name"/>

Any time the value of the owner’s name property changes, the new value will be automatically reflected in the text field’s text property, and vice versa.

For more information, see the following examples or the project README:

  • Custom Cell View – custom table view cell implemented in markup. Cell values are updated via data binding.

  • Form View – demonstrates how to create a simple form using auto layout. Data binding is used to manage the form values.

HTTP-RPC 4.0 Released

HTTP-RPC 4.0 is now available for download. This release adds support for application/x-www-form-urlencoded and application/json request encodings. In addition to submitting request arguments as multipart/form-data, client applications can now POST arguments as URL-encoded key/value pairs and POST or PUT argument values as JSON.

For example, the following Java code would submit a JSON-encoded POST request to the resource located at /example:

serviceProxy.setEncoding(WebServiceProxy.APPLICATION_JSON);

serviceProxy.invoke("POST", "/example", mapOf(
    entry("string", "hello"),
    entry("number", 123),
    entry("flag", true)), (result, exception) -> {
    // ...
});

In Swift, the code might look like this:

serviceProxy.encoding = WSApplicationJSON

serviceProxy.invoke("POST", path: "/example", arguments: [
    "string": "hello",
    "number": 123,
    "flag": true
    ]) { result, error in
    // ...
}

In either case, the body of the request would contain the following:

{
  "string": "hello",
  "number": 123,
  "flag": true
}

For more information, see the project README.

Simplifying Auto Layout in iOS

Auto layout is an iOS feature that allows developers to create applications that automatically adapt to device size, orientation, or content changes. An application built using auto layout generally has little or no hard-coded view positioning logic, but instead dynamically arranges user interface elements based on their preferred or "intrinsic" content sizes.

Auto layout in iOS is implemented primarily via layout constraints, which, while powerful, are not particularly convenient to work with. This article provides an overview of how constraints are typically managed in an iOS application, and then discusses some alternatives that can significantly simplify the task of working with auto layout.

Storyboards

The structure of an iOS user interface is commonly represented by XIB files or storyboards created using Xcode's Interface Builder utility. This tool allows developers to lay out an application's user interface visually using drag/drop and other interactive features.

For example, the following is a storyboard representing a simple view. The view contains two subviews whose positions will be automatically determined at runtime based on layout constraints. The constraints pin the subviews to the edges of the parent view as well as to each other, with a 16-pixel gap in between:

Running the application in portrait mode on an iPhone 7 produces the following results:

In lanscape mode, the application looks like this:

While storyboards are undoubtedly the most common way to define auto layout constraints, they are not necessarily the most efficient. Using Interface Builder to visually establish every relationship can be awkward, especially when working with large or complex view hierarchies. Further, storyboards are not stored in a human-readable text format, which makes it difficult to identify changes across revisions. Finally, although controller logic can be shared between projects, iOS storyboards cannot be used in a tvOS application. Separate storyboards must be created for each platform, resulting in a potentially significant duplication of effort.

Programmatically Defined Constraints

In addition to storyboards, constraints can also be managed programmatically. For example, the following Swift code produces the same results as the previous example:

func createConstraintBasedView() {
    // Red view
    let redView = UIView()

    redView.translatesAutoresizingMaskIntoConstraints = false
    redView.backgroundColor = UIColor(red: 202.0 / 255.0, green: 53.0 / 255.0, blue: 56.0 / 255.0, alpha: 1.0)

    view.addSubview(redView)

    // Blue view
    let blueView = UIView()

    blueView.translatesAutoresizingMaskIntoConstraints = false
    blueView.backgroundColor = UIColor(red: 59.0 / 255.0, green: 85.0 / 255.0, blue: 162.0 / 255.0, alpha: 1.0)

    view.addSubview(blueView)

    // Constraints
    NSLayoutConstraint.activate([
        NSLayoutConstraint(item: redView, attribute: .top, relatedBy: .equal,
            toItem: topLayoutGuide, attribute: .bottom,
            multiplier: 1.0, constant: 0.0),
        NSLayoutConstraint(item: redView, attribute: .bottom, relatedBy: .equal,
            toItem: bottomLayoutGuide, attribute: .top,
            multiplier: 1.0, constant: 0.0),
        NSLayoutConstraint(item: redView, attribute: .leading, relatedBy: .equal,
            toItem: view, attribute: .leadingMargin,
            multiplier: 1.0, constant: 0.0),

        NSLayoutConstraint(item: blueView, attribute: .top, relatedBy: .equal,
            toItem: topLayoutGuide, attribute: .bottom,
            multiplier: 1.0, constant: 0.0),
        NSLayoutConstraint(item: blueView, attribute: .bottom, relatedBy: .equal,
            toItem: bottomLayoutGuide, attribute: .top,
            multiplier: 1.0, constant: 0.0),
        NSLayoutConstraint(item: blueView, attribute: .leading, relatedBy: .equal,
            toItem: redView, attribute: .trailing,
            multiplier: 1.0, constant: 16.0),
        NSLayoutConstraint(item: blueView, attribute: .trailing, relatedBy: .equal,
            toItem: view, attribute: .trailingMargin,
            multiplier: 1.0, constant: 0.0),

        NSLayoutConstraint(item: redView, attribute: .width, relatedBy: .equal,
            toItem: blueView, attribute: .width,
            multiplier: 1.0, constant: 0.0),
    ])
}

Because the constraints are established in code, it is easy to identify changes between revisions. Additionally, this version also works in tvOS:

Unfortunately, managing constraints programmatically is not particularly convenient. This simple layout required the definition of eight individual constraints. More complex layouts could quickly become untenable.

Stack Views

The UIStackView class, introduced in iOS 9, provides an alternative to managing constraints directly. Stack views automatically arrange their subviews in a vertical or horizontal line, and can be nested to create sophisticated layouts.

For example, the following code uses a stack view to produce results identical to the first two examples. It also works in both iOS and tvOS:

func createStackView() -> UIView {
    let view = UIStackView()

    view.isLayoutMarginsRelativeArrangement = true
    view.spacing = 16

    // Red view
    let redView = UIView()

    redView.backgroundColor = UIColor(red: 202.0 / 255.0, green: 53.0 / 255.0, blue: 56.0 / 255.0, alpha: 1.0)

    view.addArrangedSubview(redView)

    // Blue view
    let blueView = UIView()

    blueView.backgroundColor = UIColor(red: 59.0 / 255.0, green: 85.0 / 255.0, blue: 162.0 / 255.0, alpha: 1.0)

    view.addArrangedSubview(blueView)

    // Width constraint
    NSLayoutConstraint.activate([
        NSLayoutConstraint(item: redView, attribute: .width, relatedBy: .equal,
            toItem: blueView, attribute: .width,
            multiplier: 1.0, constant: 0.0),
    ])

    return view
} 

While it is arguably more readable than the previous version, this example is still somewhat verbose. It also still requires the explicit creation of a layout constraint to manage the width relationship, which is not ideal.

Layout Views

MarkupKit is an open-source framework for simplifying development of native iOS and tvOS applications. Among other things, it provides the following collection of view classes, whose sole responsibility is managing the size and position of their respective subviews:

  • LMRowView – arranges subviews in a horizontal line
  • LMColumnView – arranges subviews in a vertical line
  • LMLayerView – arranges subviews in layers, like a stack of transparencies
  • LMAnchorView – optionally anchors subviews to one or more edges

These classes use layout constraints internally, allowing developers to easily take advantage of auto layout while eliminating the need to manage constraints directly.

For example, the following code uses an instance of LMRowView to replicate the results produced by the previous examples. The weight property is used to ensure that the views are the same width. This property, which is added to UIView by MarkupKit, specifies the amount of excess space the view would like to be given within its parent view, relative to all other weights. Since both views are assigned a weight of 1, they will each be given 1 / (1 + 1), or one-half, of the available space:

func createRowViewProgrammatically() -> UIView {
    let view = LMRowView()

    view.spacing = 16

    // Red view
    let redView = UIView()

    redView.backgroundColor = LMViewBuilder.colorValue("#CA3538")
    redView.weight = 1.0

    view.addArrangedSubview(redView)

    // Blue view
    let blueView = UIView()

    blueView.backgroundColor = LMViewBuilder.colorValue("#3B55A2")
    blueView.weight = 1.0

    view.addArrangedSubview(blueView)

    return view
}

Like stack views, layout views are easy to work with programmatically, and are supported in both iOS and tvOS. However, unlike stack views, no manual constraint is manipulation required; MarkupKit uses the defined weight values to automatically establish the width relationship.

Additionally, the colorValue(_) method of MarkupKit's LMViewBuilder class is used to simplify color assignment in this example. The logic is still a bit verbose though, and could become difficult to manage as view complexity increases.

Markup

MarkupKit's namesake feature is its support for declarative view construction. Using markup, the view hiearchy created in the previous example can be represented entirely as follows:

<LMRowView spacing="16">
    <UIView backgroundColor="#ca3538" weight="1"/>
    <UIView backgroundColor="#3b55a2" weight="1"/>
</LMRowView>

The markup is loaded using the view(withName:owner:root:) method of LMViewBuilder. This method is similar to the loadNibNamed(_:owner:options:) method of the NSBundle class, and returns the root element of the view hiearchy declared in the document:

func createRowViewDeclaratively() -> UIView {
    return LMViewBuilder.view(withName: "ViewController", owner: self, root: nil)!
}

Like the previous version, this example works in both iOS and tvOS. However, unlike all of the preceding examples, this version is extremely concise. It is also much more readable: the element hierarchy declared in the document parallels the resulting view hiearchy, making it easy to understand the relationships between views.

For example, the periodic table shown below was constructed using a combination of MarkupKit-provided layout views and UILabel instances:

Creating this view in Interface Builder would be an arduous task. Creating it programmatically would be even more difficult. However, in markup it is almost trivial. The complete source code for this example can be found here.

Using markup can also help promote a clear separation of responsibility within an application. Most, if not all, aspects of a view's presentation can be specified in the view declaration, leaving the view controller responsible solely for managing the view's behavior.

Summary

This article provided an overview of how layout constraints are typically managed in an iOS application, and discussed some alternatives that can significantly simplify the task of working with auto layout, including stack views, layout views, and markup.

For more information, please see the MarkupKit README.

Building a Simple Barcode Scanner in iOS

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.defaultDevice(withMediaType: AVMediaTypeVideo)
    
    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 = [
                AVMetadataObjectTypeEAN13Code,
                AVMetadataObjectTypeQRCode
            ]
    
            metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        }
    }
    
    session.commitConfiguration()
    
    cameraView.layer.session = session
    cameraView.layer.videoGravity = AVLayerVideoGravityResizeAspectFill
  • 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 captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, 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. The complete source code for the example ViewController class should look something like the following:

import UIKit
import AVFoundation

class CameraView: UIView {
    override class var layerClass: AnyClass {
        get {
            return AVCaptureVideoPreviewLayer.self
        }
    }

    override var layer: AVCaptureVideoPreviewLayer {
        get {
            return super.layer as! AVCaptureVideoPreviewLayer
        }
    }
}

class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
    // Camera view
    var cameraView: CameraView!

    // AV capture session and dispatch queue
    let session = AVCaptureSession()
    let sessionQueue = DispatchQueue(label: AVCaptureSession.self.description(), attributes: [], target: nil)

    override func loadView() {
        cameraView = CameraView()

        view = cameraView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        session.beginConfiguration()

        let videoDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

        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 = [
                    AVMetadataObjectTypeEAN13Code,
                    AVMetadataObjectTypeQRCode
                ]

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

        session.commitConfiguration()

        cameraView.layer.session = session
        cameraView.layer.videoGravity = AVLayerVideoGravityResizeAspectFill

        // Set 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
    }

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

        // Start AV capture session
        sessionQueue.async {
            self.session.startRunning()
        }
    }

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

        // Stop AV capture session
        sessionQueue.async {
            self.session.stopRunning()
        }
    }

    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
    }

    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        // Display barcode value
        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)
        }
    }
}