0

I am taking data from core data, and trying to display it using URLImage library (https://github.com/dmytro-anokhin/url-image), but it always return this error: Fatal error: Unexpectedly found nil while unwrapping an Optional value: file, even though when I'm printing the value or use Text, there's actually a value (not nil).

CartView.swift

class MyViewModel: ObservableObject, ModelService {
    @FetchRequest(
        entity: Cart.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \Cart.menuName, ascending: true)
        ]
    ) var cartItems: FetchedResults<Cart>

    var body: some View {
        VStack {
            ForEach(cartItems, id: \.self) { cat in
                    HStack {
                        if let mImg = cat.menuImg {
                            Text(mImg)
                            if mImg != nil {
                                URLImage(url: URL(string: mImg)!, // Error here: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
                                content: { image in
                                     image
                                        .resizable()
                                        .aspectRatio(contentMode: .fill)
                                        .clipped()
                                })
                            }
                        }
                }
            }
        }
    }
}

I'm thinking is there something wrong with my unwrapping the optional value? What is the correct way of doing this? thank you very much

Charas
  • 1,753
  • 4
  • 21
  • 53
  • 1
    Most likely `URL(string: mImg)` returns nil rather than the variable being nil, you should check the variable to see if it is in a proper url format. – Joakim Danielson Apr 23 '21 at 06:14
  • turns out it is not in a proper url format, which something like "Image 1", how do I catch this though so the app doesn't crash? could you please post it as answer, will do accept it – Charas Apr 23 '21 at 14:17
  • Does this answer your question? [How to encode a URL in Swift](https://stackoverflow.com/questions/24879659/how-to-encode-a-url-in-swift) – Joakim Danielson Apr 23 '21 at 14:38

0 Answers0