
This video is only available to subscribers. Start a subscription today to get access to this and 472 other videos.
Why Coordinators?
This episode is part of a series: Refactoring to Coordinators.
1. Why Coordinators? 15 min |
2. Handling Actions from Users 11 min |
3. Moving Review Logic 17 min |
4. Handling the Photo Transition 8 min |
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.