0
votes

I am trying to change the ImageView image of a view controller when it's presented. The view controller is being presented in my AppDelegate file. However, whenever the logic is triggered, the app crashes (lldb) and the error reads: "Thread 1: Unexpectedly found nil while unwrapping an Optional value." I can push ViewControllers with their default configuration, but I can't edit their variables when presenting them from AppDelegate. My code in AppDelegate is as follows:

//the viewController to present
let viewController = storyboard.instantiateViewController(withIdentifier: "myViewController") as! myViewController
viewController.imageView.image = UIImage(named: "myImage.png")

// navigationController is my instantiated navigation controller in my storyboard
navigationController.pushViewController(viewController, animated: true)

I also made my own pushViewController extension that accommodates a completion hander:

navigationController.pushViewController(viewController, animated: true, completion: {
                viewController.imageView.image = UIImage(named: "myImage.png")
            })

This still didn't work unfortunately. It works fine when I do this in other files that aren't AppDelegate. For some reason I can't get it to work in AppDelegate. Any help would be greatly appreciated!

1
A very common mistake. At the moment the view controller is instantiated the outlets are not connected yet. Use a property to pass the image and assign the image to the image view in viewDidLoad of myViewController. And according to the naming convention class names start with a capital letter.vadian

1 Answers

0
votes

Check out this. Try using guard statement in instantiating the viewController from the storyboard and avoid forced casting.

    guard let viewController = storyboard.instantiateViewController(withIdentifier: "myViewController") as? myViewController 
else { return false }
viewController.imageView?.image = UIImage(named: "myImage.png")