swift 5 display image from url in a list code example
Example 1: uiimage swift src url
let imageCache = NSCache<AnyObject, AnyObject>()
class CustomImageView: UIImageView {
var ImageUrlString: URL?
func setImage(from url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
contentMode = mode
ImageUrlString = url
if let imageFromCache = imageCache.object(forKey: url as AnyObject) {
self.image = imageFromCache as? UIImage
return
}
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 imageToCache = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
if self.ImageUrlString == url {
self.image = imageToCache
}
imageCache.setObject(imageToCache, forKey: url as AnyObject)
}
}.resume()
}
func setImage(from link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
setImage(from: url, contentMode: mode)
}
}
Example 2: Loading/Downloading image from URL on Swift
extension UIImageView {
func downloaded(from 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() {
self.image = image
}
}.resume()
}
func downloaded(from link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloaded(from: url, contentMode: mode)
}
}
imageView.downloaded(from: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")