如何使用URL Swift 3下载图像?

Hen*_*nry 1 ios swift swift3

我是一个新手开发者,我正在尝试从URL下载并显示图像并将其显示在UIImage视图中.我尝试了多种方法,使用以前问过的问题和网页信息,但它不断出现多个错误.

小智 14

这里有一个很好的例子,说明如何在Leo Dabus的答案中做到这一点.我将在下面的问题中包含相关位.

使用该帖子中的代码,我发现一种更简单,更简洁的方法是添加扩展名UIImageView:

extension UIImageView {
    func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
                else { return }
            DispatchQueue.main.async() { () -> Void in
                self.image = image
            }
        }.resume()
    }
    func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloadedFrom(url: url, contentMode: mode)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用以下命令从视图控制器中获取图像:

if let url = URL.init(string: urlString) {
    imageView.downloadedFrom(url: url)
}
Run Code Online (Sandbox Code Playgroud)

  • https://stackoverflow.blog/2009/06/attribution-required/ (3认同)