3

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.

Henry
  • 339
  • 2
  • 4
  • 14
  • 3
    Pick one of these multiple methods you've implemented and post the code for it, and what errors you are getting. – Gruntcakes Dec 13 '16 at 23:09

1 Answers1

16

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)
}
Community
  • 1
  • 1
Kevin Aleman
  • 393
  • 3
  • 9
  • 3
    https://stackoverflow.blog/2009/06/attribution-required/ – Leo Dabus Dec 13 '16 at 23:33
  • 1
    @LeoDabus fixed and thanks for the excellent work on your answers on this site. They helped me immensely when I started learning Swift. – Kevin Aleman Dec 13 '16 at 23:40
  • let url = URL(string:headerViewImageUrl) let data = try? Data(contentsOf: url!) let img: UIImage = UIImage(data: data!)! imageview.imgage = img – Chandramani May 25 '17 at 08:36