Gabriele Filosofi Gabriele Filosofi - 7 months ago 90
iOS Question

Xcode8 Swift3 iOS10: 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: "")
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


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.