Applying Style Sheets Client-Side in iOS

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

While native mobile applications can often provide a more seamless and engaging user experience than a browser-based app, it is occasionally convenient to present certain types of content using a web view. Specifically, any content that is primarily text-based and requires minimal user interaction may be a good candidate for presentation as HTML; for example, product descriptions, user reviews, or instructional content.

However, browser-based content often tends to look out of place within a native app. For example, consider the following simple HTML document:



Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
  • Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
  • Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
  • Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Rendered by WKWebView, the result looks like this:

Because the text is displayed using the default browser font rather than the system font, it is immediately obvious that the content is not native. To make it appear more visually consistent with other elements of the user interface, a stylesheet could be used to render the document using the system font:

    body {
        font-family: '-apple-system';
        font-size: 10pt;

The result is shown below. The styling of the text now matches the rest of the UI:

However, while this approach may work for this simple example, it does not scale well. Different app (or OS) versions may have different styling requirements.

By applying the stylesheet on the client, the presentation can be completely separated from the content. This can be accomplished by linking to the stylesheet rather than embedding it inline:


However, instead of downloading the stylesheet along with the HTML document, it is distributed with the application itself and applied using the load(_:mimeType:characterEncodingName:baseURL:) method of the WKWebView class. The first argument to this method contains the (unstlyed) HTML content, and the last contains the base URL against which relative URLs in the document (such as stylesheets) will be resolved:

class ViewController: UIViewController {
    var webView: WKWebView!

    override func loadView() {
        webView = WKWebView()

        view = webView

    override func viewDidLoad() {

        title = "Client-Side CSS"

        if let url = Bundle.main.url(forResource: "example", withExtension: "html"),
            let data = try? Data(contentsOf: url),
            let resourceURL = Bundle.main.resourceURL {
            webView.load(data, mimeType: "text/html", characterEncodingName: "UTF-8", baseURL: resourceURL)

In this example, the document, example.html, is loaded from the main bundle. In a real application, it would most likely be loaded from an actual web server.

The stylesheet, example.css, is stored in the resource folder of the application’s main bundle:

body {
    font-family: '-apple-system';
    font-size: 10pt;

The results are identical to the previous example. However, the content and visual design are no longer tightly coupled and can vary independently:

Complete source code for this example can be found here.

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:
to scan barcodes

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.

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() {
        activityIndicatorView = UIActivityIndicatorView(style: .gray)
        tableView.backgroundView = activityIndicatorView
    override func 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) {

    if (rows == nil) {

        tableView.separatorStyle = .none

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

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


                self.tableView.separatorStyle = .singleLine

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 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!