[ad_1]
I’ve attempting to unravel this drawback nevertheless I’m not positive methods to proceed.
Mainly picture is downloaded after which this class operate is handed inside which shops the picture in cache and reasonably than downloading it once more, we will use the already saved information from the cache.
As you may see it may possibly simply be carried out utilizing NSCache. Nevertheless the problem particularly says to finish this with out the usage of NSCache.
/*
Implement `DefaultImageCache` conforming the `ImageCache` protocol.
---
The category ought to help:
- storage of a `UIImage` recognized by a singular key (`setImage`)
- retrieval of a `UIImage` by key (`getImage`)
---
Be aware: to be carried out with out utilizing NSCache
*/
remaining class DefaultImageCache: ImageCache {
func setImage(_ picture: UIImage?, key: String) {
// TODO
}
func getImage(forKey key: String) -> UIImage? {
// TODO
nil
}
}
protocol ImageCache {
func setImage(_ picture: UIImage?, key: String)
func getImage(forKey key: String) -> UIImage?
}
My answer that I’ve carried out is beneath :
Utilizing the fileManager to retailer the downloaded recordsdata. Nevertheless that doesn’t looks like the proper manner as it’s saved completely and it could not be cache.
func setImage(_ picture: UIImage?, key: String) {
if let picture = picture {
if let information = picture.jpegData(compressionQuality: 0.9) {
let filename = getDocumentsDirectory().appendingPathComponent(key.replacingOccurrences(of: "https://pictures.punkapi.com/v2/", with: ""))
strive? information.write(to: filename)
}
}
func getImage(forKey key: String) -> UIImage? {
let fileURL = getDocumentsDirectory().appendingPathComponent(key.replacingOccurrences(of: "https://pictures.punkapi.com/v2/", with: ""))
do {
let consequence = strive Knowledge(contentsOf: fileURL)
return UIImage(information: consequence)
} catch {
return nil
}
}
Please information for a greater answer.
How would I obtain Cache performance with out the usage of NSCache?
[ad_2]
