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.
Asked
Active
Viewed 1.4k times
1 Answers
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
-
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