How to download image with URL Swift 3?

Solutions Collect From Internet About “How to download image with URL Swift 3?”

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.

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