Gabriele Filosofi Gabriele Filosofi - 1 year ago 73
iOS Question

Cannot download image using URLSession

I'm stuck on how to correctly use a

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

let url = URL(string: "")
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

Answer Source

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 – that's the actual JPEG file you're looking for.