Swift 3 Extension to UIImage to quickly retrieve image from a URL

Andrew Kouri
andrewkouri
Published in
1 min readFeb 3, 2017

I spent too long looking for a quick, non-deprecated solution to this simple problem this morning. Here’s what I came up with. Maybe it will save you a few minutes of searching. This is valid for Swift 3.

Since I have tableViewCells that need to set images from a URL string, I figured it would be best to make an extension that could be called on the cell configuration:

The extension:

extension UIImageView {
public func image(fromUrl urlString: String) {
guard let url = URL(string: urlString) else {
log.warning("Couldn't create URL from \(urlString)")
return
}
let theTask = URLSession.shared.dataTask(with: url) {
data, response, error in
if let response = data {
DispatchQueue.main.async {
self.image = UIImage(data: response)
}
}
}
theTask.resume()
}
}

Usage is a one-liner

cell.productImage.image(fromUrl: order.product.imageUrl)

--

--