Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Displaying an Activity Indicator while Loading Table View Data

DZone's Guide to

Displaying an Activity Indicator while Loading Table View Data

Let your users know about long running tasks with activity indicators.

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

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. In viewDidLoad, the controller creates the activity indicator view and sets it as the table view's background view. 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:

class ViewController: UITableViewController {
    weak var activityIndicatorView: UIActivityIndicatorView!

    var rows: [String]! = nil

    let cellIdentifier = "cell"

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Activity Indicator Example"

        let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)

        tableView.backgroundView = activityIndicatorView
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None

        self.activityIndicatorView = activityIndicatorView

        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
    }

    ...
}

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 enabled while the background operation is executing, and is disabled when the operation is complete:

class ViewController: UITableViewController {
    ...

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

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

            AppDelegate.operationQueue.addOperationWithBlock() {
                NSThread.sleepForTimeInterval(3)

                NSOperationQueue.mainQueue().addOperationWithBlock() {
                    self.activityIndicatorView.stopAnimating()

                    self.rows = ["One", "Two", "Three", "Four", "Five"]

                    self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
                    self.tableView.reloadData()
                }
            }
        }
    }

    ...
}

Image title

Finally, the controller overrides numberOfSectionsInTableView:, tableView: numberOfRowsInSection:, and tableView:cellForRowAtIndexPath: to provide the table content. It reports zero sections while the data is being loaded, and one section once the data is available:

class ViewController: UITableViewController {
    ...

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

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)!

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

        return cell
    }
}

Image title

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:
ios ,multithreading ,ui ,mobile

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}