Why Coordinators?

Episode #268 | 15 minutes | published on May 9, 2017 | Uses iOS-10.3, Xcode-8.3
What is the Coordinators pattern, and why is it useful? Soroush and Ben discuss this and then get started refactoring an existing application that uses Storyboards into using Coordinators. We implement our first AppCoordinator and wire it up on launch.

Episode Links

  • Source Code
  • The Coordinator - Soroush's original blog post on the topic and the inspiration for this series. Take a minute and read up on it and see why this pattern might be useful to you.
  • Coordinators Redux - A longer follow-up article from Soroush on real-world usage.

The Setup

We want to be in control of the root view controller, so let's remove this responsibility from the Storyboard. Going into project settings, we can delete the Main Interface setting.

This will require us to set up a root view controller on our window manually.

window = UIWindow()

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nav = storyboard.instantiateInitialViewController() as! UINavigationController
window?.rootViewController = nav      

A Bare-Bones App Coordinator

Your app might be complicated enough to justify different coordinators, but let's just start with a single one for the app. We'll call it AppCoordinator.

class AppCoordinator {
    let navigationController: UINavigationController

    init(navigationController: UINavigationController) {
        self.navigationController = navigationController
    }

    func start() {
    }
}

Here we hold a reference to our root view controller, and have an empty start() method.

Wiring it Up

Back in the AppDelegate we'll add another property, add a new property for our coordinator instance:

var coordinator: AppCoordinator?

Then, after creating the window and root view controller, we'll create the coordinator instance, passing it the navigation controller:

coordinator = AppCoordinator(navigationController: nav)
coordinator?.start()

We can add custom presentation logic, for instance, to the start() method. For now, it's blank.

Finally, we need to make the window active:

window.makeKeyAndVisible()

Make sure it works

We've just made a tiny bit of surgery to our application boot process, but we need to check to make sure it still works. Run the app and make sure there are no issues.

We've now taken the first step to use Coordinators. Next time we'll see how we can leverage this pattern to see some real benefits.

blog comments powered by Disqus