如何使用URL Swift 3下载图像? [英] How to download image with URL Swift 3?

查看:141
本文介绍了如何使用URL Swift 3下载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im a newbie dev and I'm trying to download and display an image from a URL and display it in a UIImage view. I've tried a multiple methods using info from previously asked questions and thr web but it keeps coming up with multiple errors.

推荐答案

Leo Dabus的回答。我将在下面的问题中包含相关位。

There's an excellent example of how to do this in Leo Dabus's answer here. I'll include the relevant bits to your question below.

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

Using code from that post, I've found one of the easier and cleaner ways is to add an extension to 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)
    }
}

然后您可以使用以下方式从视图控制器中获取图像:

Then you can just grab the image from your view controller using:

if let url = URL.init(string: urlString) {
    imageView.downloadedFrom(url: url)
}

这篇关于如何使用URL Swift 3下载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆