How do I do dependency injection for the first screen view controller when using a storyboard?

When writing code by hand, we can inject the dependencies of the rootViewController by embedding the constructor in the AppDelegate:

UIViewController *vc = [[SomeViewController alloc] initWithDependency: dependency];
self.window.rootViewController = vc;

      

However, I cannot find a way to inject dependencies when using Storyboard. It seems inappropriate to inject them into awakeFromNib

or viewDidLoad

etc.

Can I insert them?

+3


source to share


1 answer


In your AppDelegate, check the following code:



func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let dependency = MyDependency()
    if let firstVC = window?.rootViewController as? MyViewControllerClass {
        firstVC.dependency = dependency
    }

    return true
}

      

0


source







All Articles