Dakata
Dakata

Reputation: 1355

Unexpectedly found nil when opening an UIImage

I am developing a Walkthrough screen where I have added 3 instruction images which help the users to work with the application. The problem occurs, when I first launch the app I see only the labels with the "instruction tekst" , but below this label the user should also see the images. Maybe I am doing something wrong, attached I uploaded a picture of the error: enter image description here

And here I upload the picture of the code I have used to transfer these picture to the TutorialPageContentHolderViewController: enter image description here I would be very thankful if you see my mistake, because I have been struggling with that the whole day.

Upvotes: 1

Views: 846

Answers (1)

Bogdan Farca
Bogdan Farca

Reputation: 4106

I guess the imageFileName variable in your first image is nil when you use it in

myImageView.image = UIImage(named: imageFileName)

When you assign it a value in the second screenshot it could be too late, as viewdidLoad is loaded before that. You could check if this is true by manually assigning a valid value to imageFileName before using it and see if it works.

One simple way to fix it would be to add an initialiser to the view controller class, pass the filename as a parameter and store the filename in a local variable until you use it in viewDidLoad.

A second way would be to add a method to the page view controller as below (and remove the corresponding line from viewDidLoad):

func prepare(with filename:String) {
    myImageView.image = UIImage(named: filename)
}

and call it from the pageTutorialAtIndex method in your main view controller.

Upvotes: 1

Related Questions