Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 542
Gabriele Filosofi Avatar asked Sep 20 '26 05:09

Gabriele Filosofi


1 Answers

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.

like image 111
TwoStraws Avatar answered Sep 22 '26 19:09

TwoStraws