Dans cet article, nous verrons comment mettre en cache des images dans une application Swift pour améliorer les performances de…
Dec 03 2022
.
import UIKit
class ImageCache {
// MARK: - Properties
private let cache = NSCache<NSString, UIImage>()
// MARK: - Caching
func cache(image: UIImage, forKey key: String) {
cache.setObject(image, forKey: key as NSString)
}
func image(forKey key: String) -> UIImage? {
return cache.object(forKey: key as NSString)
}
}
let cache = ImageCache()
let image = UIImage(named: "myImage")
cache.cache(image: image, forKey: "myImage")
let cachedImage = cache.image(forKey: "myImage")
import UIKit
extension UIImageView {
private struct AssociatedKeys {
static var imageCache = "imageCache"
}
var imageCache: ImageCache {
get {
if let cache = objc_getAssociatedObject(self, &AssociatedKeys.imageCache) as? ImageCache {
return cache
}
let cache = ImageCache()
objc_setAssociatedObject(self, &AssociatedKeys.imageCache, cache, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return cache
}
}
func cache(image: UIImage, forKey key: String) {
imageCache.cache(image: image, forKey: key)
}
func cachedImage(forKey key: String) -> UIImage? {
return imageCache.image(forKey: key)
}
}
import UIKit
class ImageCache {
// MARK: - Properties
private let cache = NSCache<NSString, UIImage>()
// MARK: - Caching
func cache(image: UIImage, forKey key: String) {
cache.setObject(image, forKey: key as NSString)
}
func image(forKey key: String) -> UIImage? {
return cache.object(forKey: key as NSString)
}
func clearCache() {
cache.removeAllObjects()
}
func loadImage(fromURL url: URL, forKey key: String, completion: @escaping (UIImage?) -> Void) {
if let image = image(forKey: key) {
completion(image)
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data, let image = UIImage(data: data) {
self.cache(image: image, forKey: key)
completion(image)
} else {
completion(nil)
}
}.resume()
}
}
let cache = ImageCache()
let imageURL = URL(string: "https://example.com/image.png")!
cache.loadImage(fromURL: imageURL, forKey: "imageKey") { image in
// Use the image here
}
cache.clearCache()