Charlotte L.
Charlotte L.

Reputation: 173

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

func loadImageFromUrl() {

        guard let urlString = self.urlString else {
        return
    }

    let url = URL(string: urlString)!
        let task = URLSession.shared.dataTask(with: url, completionHandler: self.getImageFromResponse(data:response:error:))
        task.resume()
}

I keep on getting this fatal error (mentioned in title) for let url = URL(string: urlString)!, even if I have tried to guard it in previous lines. Also, when I move my cursor over urlString, it indeed shows a highlight of my intended url from the API.

Upvotes: 1

Views: 1670

Answers (2)

Asperi
Asperi

Reputation: 257711

This should work

if let url = URL(string: urlString) {
    let task = URLSession.shared.dataTask(with: url, 
       completionHandler: self.getImageFromResponse(data:response:error:))
    task.resume()
}

Upvotes: 0

New Dev
New Dev

Reputation: 49590

url could still be nil, if urlString doesn't represent a valid URL. You haven't guarded against that; you've only guarded against urlString not being nil.

You need to guard against both possible outcomes:

func loadImageFromUrl() {

   guard let url = URL(string: self.urlString) else {
      print("Invalid url string: \(self.urlString)")
      return
   }

   let task = URLSession.shared.dataTask(with: url, ....

   // rest of your code
}

Of course, that doesn't solve the underlying problem that urlString is indeed broken. You need to see what's going on there.

Since you're visually seeing that it's correct, it's possible that it contains some whitespace at the beginning or the end. If it's not a urlString that you control, you can trim it:

let trimmedUrlStr = self.urlString.trimmingCharacters(in: .whitespacesAndNewlines)

Upvotes: 3

Related Questions