0

My intention is to initialize a view controller and set it to the window rootViewController, then pass the view controller as dependency to an AppCoordinator where the app decide what to do with the view controller (replace it with an onboarding scene or login page, or even home screen if the user is already logged in.

The problem is that whenever I do that, the window doesn't seems to get back its view controller, but instead a black screen.

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    self.window = UIWindow(windowScene: windowScene)
    var viewController = UIViewController()
    self.window?.rootViewController = viewController
    let appCoordinator = AppCoordinator(viewController: viewController)
    appCoordinator.start()
    window?.makeKeyAndVisible()
}

AppCoordinator.swift

import UIKit
import SwiftUI
class AppCoordinator: Coordinator {
    var viewController: UIViewController
    init(viewController: UIViewController) {
        self.viewController = viewController
    }
    func start() {
        let onboardingView = OnboardingView()
        self.viewController = UIHostingController(rootView: onboardingView)
    }
}

If I bypass the AppCoordinator and set everything in the scene delegate, the screen loads correctly:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    self.window = UIWindow(windowScene: windowScene)
    var viewController = UIViewController()
    let onboardingView = OnboardingView()
    self.window?.rootViewController = UIHostingController(rootView: onboardingView)
    window?.makeKeyAndVisible()
}

What seems to be wrong when I pass the view controller as a dependency? Btw, I don't prefer to pass the window as dependency to the called coordinator, although this works, I don't prefer it.

Yogesh Patel
  • 1,893
  • 1
  • 20
  • 55
Malloc
  • 15,434
  • 34
  • 105
  • 192

0 Answers0