How to download image with URL Swift 3?
13,660
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)
}
Comments
-
Henry almost 2 years
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 over 7 years
-
Kevin Aleman over 7 years@LeoDabus fixed and thanks for the excellent work on your answers on this site. They helped me immensely when I started learning Swift.
-
Chandramani almost 7 yearslet url = URL(string:headerViewImageUrl) let data = try? Data(contentsOf: url!) let img: UIImage = UIImage(data: data!)! imageview.imgage = img