Want to offer native, in-app customer service to your users? Get going quickly with Zendesk’s Mobile SDKs. Free with Zendesk.

Today we'll checkout another great library from Alexander Schuch called StatefulViewController.

It can help us add loading, empty, and error states to our view controllers. Let's get started:

Most apps we build must load data before showing it to the user. Those apps will also need to handle the case where there's no data available, or when something goes wrong.

StatefulViewController allows us to easily add all of this functionality to our view controllers.

While this might seem trivial, there's actually quite a bit of logic and state management involved. StatefulViewController helps eliminate boilerplate and help us focus on building the parts of our app that make it unique and useful.

Let's try it out. First, we'll make a view controller, and adopt the protocol:

class ViewController: UIViewController, StatefulViewController { }

Then we'll need to set up our placeholder views:

// inside viewDidLoad
loadingView = LoadingView(frame: view.frame)
emptyView = EmptyView(frame: view.frame)
errorView = ErrorView(frame: view.frame)

Next, we'll need to set up the initial state when the view controller's view is about to appear:

override func viewWillAppear(animated: Bool) {

Now we can visually start and stop loading when we need:

endLoading(error: nil)

Lastly, we'll need to implement one more function to let the library know when there's content available:

func hasContent() -> Bool {
  return spaceships.count > 0

More info about StatefulViewController can be found at git.io/stateful