Coordinator iOS
I am using the coordinator pattern on my Counter App. These are the steps to implement the coordinator pattern.
1. Create a Coordinator protocol.
| |
2. Create a class that implements the Protocol
I normally use AppCoordinator.swift:
| |
The start function is where it’ll initialize our “root” controller. For this case, I’m initializing the DashboardViewController. I’m using a modified version of a Protocol by [Paul Hudson]https://www.hackingwithswift.com/about) called Storyboarded. Storyboarded simplifies the instantiation of specific ViewControllers (you should add an Identifier in the Attributes inspector on the Storyboard for your UIViewControllers for it to work).
| |
All my Controllers implement the Storyboarded protocol and have an instance of coordinator. My controllers communicate with the coordinator about any event that changes the flow of the App. The coordinator is responsible for handling the workflow of the App, deciding whom to call and instantiate.
3. Initialize the Coordinator in AppDelegate
Now we have to tell the AppDelegate that when the application loads initialize the coordinator so, it can start “coordinating”.
The AppDelegate.swift handles all the lifecycle of the app(going to background, initializing, being dismissed, etcetera). Inside didFinishLaunchingWithOptions , we initialize the coordinator.
| |
Usually, the App does all the window creation and presentation, but because we are taking control of the boot of the App, we have to do that too. That is why we create the window, assign the rootViewController and make it visible.
That’s it.
References and resources
- http://khanlou.com/2015/01/the-coordinator/
- https://www.hackingwithswift.com/articles/71/how-to-use-the-coordinator-pattern-in-ios-apps
- https://www.hackingwithswift.com/articles/175/advanced-coordinator-pattern-tutorial-ios