Created
April 21, 2022 19:03
-
-
Save SergLam/6c7aa1a7599fc52f45582d22e8c57a4d to your computer and use it in GitHub Desktop.
Swift Extension for iOS: Load image from URL + set to an 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 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