无法使用 URLSession 下载图像

Cannot download image using URLSession

我无法正确使用 URLSession 任务将 J.S.Bach 图像下载到 UIImage。 这是viewDidLoad里面的代码。不会发生崩溃。程序永远不会到达最里面的 if 语句,并且 UIImageView 保持空白。

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()

您正在尝试将网页加载到 UIImage 实例中。我怀疑您的 URLRequest 工作正常,但是 if let bach 行卡住了,因为您正试图从一些 HTML 中创建一个 UIImage。我意识到维基百科 URL 在其路径扩展名中有“.jpg”,但它仍然指向 HTML 页面。

要解决您的问题,请尝试将 URL 更改为 https://upload.wikimedia.org/wikipedia/commons/6/6a/Johann_Sebastian_Bach.jpg – 这就是您要查找的实际 JPEG 文件。