Skip to content

Instantly share code, notes, and snippets.

@SergLam
Created April 21, 2022 19:03
Show Gist options
  • Save SergLam/6c7aa1a7599fc52f45582d22e8c57a4d to your computer and use it in GitHub Desktop.
Save SergLam/6c7aa1a7599fc52f45582d22e8c57a4d to your computer and use it in GitHub Desktop.
Swift Extension for iOS: Load image from URL + set to an UIImageView
import UIKit
extension UIImageView {
func downloadImage(from url: URL) {
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 {
self.image = image
}
}.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment