Gabriele Filosofi Gabriele Filosofi - 1 month ago 18
iOS Question

Cannot download image using URLSession

I'm stuck on how to correctly use a

URLSession
task to download a J.S.Bach image into a
UIImage
.
This is the code inside
viewDidLoad
. No crashes occur. The program never reaches the innermost if statement, and
UIImageView
remains blank.

let url = URL(string: "https://it.wikipedia.org/wiki/File:Johann_Sebastian_Bach.jpg")
let request = URLRequest(url: url!)
let task = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
if error != nil {
print("some error!")
} else {
if let bach = UIImage(data: data!) {
self.image.image = bach
}
}
})
task.resume()

Answer

You're trying to load a web page into a UIImage instance. I suspect your URLRequest is working fine, but the line if let bach chokes because you're trying to create a UIImage out of some HTML. I realize the Wikipedia URL has ".jpg" in its path extension, but it still points to a HTML page.

To fix your problem, try changing the URL to be https://upload.wikimedia.org/wikipedia/commons/6/6a/Johann_Sebastian_Bach.jpg – that's the actual JPEG file you're looking for.