Skip to content

Instantly share code, notes, and snippets.

@jmfdz
Created November 27, 2016 09:38
Show Gist options
  • Save jmfdz/ad71b1b8b30bc3ff23130f8d692acab1 to your computer and use it in GitHub Desktop.
Save jmfdz/ad71b1b8b30bc3ff23130f8d692acab1 to your computer and use it in GitHub Desktop.
Swift Extension for iOS: Load image from URL and put In UIImageView
import Foundation
import UIKit
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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment