Fatal error: Unexpectedly found nil while unwrapping an Optional value SwiftUI AnimatedImage

Viewed 460

I'm using SDWebImage to display images from a firestore database and currently getting the error:

Fatal error: Unexpectedly found nil while unwrapping an Optional value.

Not quite certain how to do the if check to prevent the force unwrapping so would appreciate if anyone can show me an alternate syntax example.

@ObservedObject var movies = getMoviesData()

...

ForEach(self.movies.datas) { item in
        VStack {
             Button(action: {}) {
                 AnimatedImage(url: URL(string: item.img)!)
                  .resizable()
                  .frame(height: 425)
                  .padding(.bottom,15)
                  .cornerRadius(5)                           
              }
         }
}

Also tried comparing to nil (as suggested in the article: What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?) but not working.

enter image description here

1 Answers

The issue is that you're comparing an unwrapped value with nil. Your program crashes even before the comparison.

You need to compare an optional value instead:

if (URL(string: item.img) != nil) { ... }

Better even to use if-let to make sure that url is not nil:

Button(action: {}) {
    if let url = URL(string: item.img) {
        AnimatedImage(url: url)
            .resizable()
            .frame(height: 425)
            .padding(.bottom, 15)
            .cornerRadius(5)
    }
}
Related