Search code examples
swiftxcodeexc-bad-access

EXC_BAD_ACCESS when using instantiateViewController


I'm trying to make a Home Screen Quick action to open a specific view controller, when I run the app I get a Thread 1: EXC_BAD_ACCESS (code=261, address=0xdac11530) error on the line shown below. Any ideas as to solve this?

func navigateToMoreDoggosVC() {
        
        let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
        let moreDoggosVC = storyBoard.instantiateViewController(withIdentifier: "moreDoggosViewController") //Thread 1: EXC_BAD_ACCESS (code=261, address=0x********)
        let navVC = self.window?.rootViewController as? UINavigationController
        
        navVC?.pushViewController(moreDoggosVC, animated: true)
        
    }

if you need any more info i would be happy to edit the question.


Solution

  • You can't push a view controller on launching the app. You need to set a rootViewController and then make it makeKeyAndVisible.

    How can we achieve this see below code:

    func navigateToMoreDoggosVC() {
        let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
        let moreDoggosVC = storyBoard.instantiateViewController(withIdentifier: "moreDoggosViewController")
        window?.rootViewController = UINavigationController(rootViewController: moreDoggosVC)
        window?.makeKeyAndVisible()
    }
    

    You need to add this code in the SceneDelegate.swift file and call it from the willConnectTo function.

    enter image description here