0

I'm using the following code to display images in a uiimage. When i use an url for an image that has the file extension it works fine.

Example image url that works: https://mysite23423.com/image.jpg

But when I use an image that my server serves thats missing the file extension in the url it doesnt display it.

Example image url that doesnt works: https://mysite23423.com/image

How can I correct this issue?

func loadImage(urlString: String) {
    lastURLUsedToLoadImage = urlString
    image = nil

    if let cachedImage = imageCache[urlString] {
        image = cachedImage
        return
    }

    guard let url = URL(string: urlString) else { return }
    URLSession.shared.dataTask(with: url) { (data, response, err) in
        if let err = err {
            print("Failed to fetch post image:", err)
            return
        }

        if url.absoluteString != self.lastURLUsedToLoadImage { return }

        guard let imageData = data else { return }
        let photoImage = UIImage(data: imageData)
        imageCache[url.absoluteString] = photoImage

        DispatchQueue.main.async {
            self.image = photoImage
        }
    }.resume()
}
user2423476
  • 2,115
  • 8
  • 28
  • 40
  • What does your code actually do with that 2nd URL? – rmaddy Jun 05 '19 at 04:03
  • It doesnt load the image. Just a blank uiimage. If I add an image with a .jpg extension it loads fine – user2423476 Jun 05 '19 at 13:59
  • No, what does your code actually do? Use the debugger and step through the code. What happens exactly inside the `dataTask` completion block? Do any of the `if` or `guard` statements trigger? Is `photoImage` nil? – rmaddy Jun 05 '19 at 15:30
  • I used the solution found here: https://stackoverflow.com/questions/4147311/finding-image-type-from-nsdata-or-uiimage/5042365#5042365 – user2423476 Jun 06 '19 at 03:20

0 Answers0