Created
November 27, 2016 09:38
-
-
Save jmfdz/ad71b1b8b30bc3ff23130f8d692acab1 to your computer and use it in GitHub Desktop.
Swift Extension for iOS: Load image from URL and put In UIImageView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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