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.