Clicky

iOS Dev Nugget 218 Display an Empty Screen While Loading Data Instead of Blocking

.

Need to run a code review on your codebase? Hire me

Using a view controller (or rather its view) to display content is a very standard operation in iOS apps. Here's a common way to do it:

let detailVC = DetailViewController()
vc.navigationController?.pushViewController(detailVC, animated: true)

DetailViewController performs one or more network operations, fetching data from a remote server and then displays the results to the user.

What we sometimes get wrong is writing a function like displayActivityIndicatorView() to display an instance of UIActivityIndicatorView in the middle of the screen blocking all interaction, including tapping the back/close/cancel button to cancel the operation until the data is available:

class DetailViewController: UIViewController {
    override func viewDidLoad() {
        displayActivityIndicatorView()
        loadDataOverNetworkSyncAndDisplay()
        hideActivityIndicatorView()
    }

    func loadDataOverNetworkSyncAndDisplay() {
        self.fetchDataByCallingAPI()
        self.displayFetchedData()
    }
}

This is bad UI and makes the user feel like they do not have control since they can't interact with the app while waiting for the data to load.

I prefer to display an empty screen (or preferably displaying cached data), and when the data is fetched, update the screen:

class DetailViewController: UIViewController {
    override func viewDidLoad() {
        displayWhateverDataIsAvailable()
        loadDataOverNetworkAsyncAndDisplay()
    }

    func loadDataOverNetworkAsyncAndDisplay() {
        DispatchQueue.global().async {
            self.fetchDataByCallingAPI()
            DispatchQueue.main.async {
                self.displayFetchedData()
            }
        }
    }
}

This lets the user cancel the operation if they like and if there's cached data displayed, interact with it.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues