Search code examples
iosswiftcastingreachability

can't cast LaunchViewController to UINavigationController


I am trying to check the network status from the AppDelegate.swift instead of checking from LaunchViewController.

I have written showOfflinePage in AppDelegate when I shut down my network I have this error cast

Could not cast value of type 'reachability_playground.LaunchViewController' (0x1095b5f20) to 'UINavigationController' (0x114bb2a20). 2019-01-06 16:42:04.079430-0500 reachability-playground[2781:93635] Could not cast value of type 'reachability_playground.LaunchViewController' (0x1095b5f20) to 'UINavigationController' (0x114bb2a20).

   private func showOfflinePage() -> Void {
        DispatchQueue.main.async {
            let storyboard = UIStoryboard(name: "Main", bundle: nil);
            let viewController: LaunchViewController = storyboard.instantiateViewController(withIdentifier: "LaunchViewController") as! LaunchViewController;

            // Then push that view controller onto the navigation stack
            let rootViewController = self.window!.rootViewController as! UINavigationController
            rootViewController.pushViewController(viewController, animated: true);
        }
    }

Solution

  • As per the exception message, your root view controller is an instance of LaunchViewController, not an instance of UINavigationController so the forced downcast fails.

    You need to check your storyboard and ensure that the entry point scene is a navigation controller.