0

I followed this tutorial for adding a gif to Xcode.

I've read this classic "unexpectedly found nil" answer from start to finish. Unfortunately, I found it to be gibberish because I am a total noob*.

This is my code:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


        var imageNames = ["giphy-1 .jpg","giphy-2 .jpg", "giphy-3 .jpg", "giphy-4 .jpg", "giphy-5 .jpg"]

        var images = [UIImage]()


        for i in 0..<imageNames.count{

                images.append(UIImage(named: imageNames[i])!)

        }

        theGif.animationImages = images
        theGif.animationDuration = 1.0
        theGif.startAnimating()

I asked Philip Lesback for help and he told me to add another ! at the end. That did not work.

*****(If it bothers you that I know nothing, please know that I've tried Code Academy, Free Code Camp, Khan Academy coding, and started multiple books but I am...hopeless, I suppose? I've tried. What seems to work best for me is video tutorials.)

Community
  • 1
  • 1
ender
  • 1

2 Answers2

2

As you said your error is a classic here in StackOverflow so far, I'll tell you how to avoid and of course why you're facing it.

Let's start with the origin of the error, you are using the failable initializer of the class UIImage, this mean that this init can return nil.

According to Apple:

The init returns the image object for the specified file, or nil if the method could not find the specified image.

Son in your case the images with that name can not be found in the application’s main bundle.

To avoid the runtime error is always recommended that you use optional-binding instead of force-unwrapping the optional value, like in this way:

var imageNames = ["giphy-1 .jpg","giphy-2 .jpg", "giphy-3 .jpg", "giphy-4 .jpg", "giphy-5 .jpg"]

var images = [UIImage]()

for i in 0..<imageNames.count{
   if let image = UIImage(named: imageNames[i]) {
       images.append(image)
   }
}

I hope this help you.

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
1

The error specifically for your case is due to the following line:

var imageNames = ["giphy-1 .jpg","giphy-2 .jpg", "giphy-3 .jpg", "giphy-4 .jpg", "giphy-5 .jpg"]

You need to remove the space between the image name and the image format, which, thus, would become:

var imageNames = ["giphy-1.jpg", "giphy-2.jpg", "giphy-3.jpg", "giphy-4.jpg", "giphy-5.jpg"]

That was what my intuition told me when I first looked at the question; but to be sure, I decided to run a quick test for both cases, which is confirming to what I guessed initially.

Unheilig
  • 16,196
  • 193
  • 68
  • 98