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

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)")
        let theTask = URLSession.shared.dataTask(with: url) {
            data, response, error in
            if let response = data {
                DispatchQueue.main.async {
                    self.image = UIImage(data: response)

Usage is a one-liner
cell.productImage.image(fromUrl: order.product.imageUrl)

Leave a Reply

Your email address will not be published. Required fields are marked *