SwiftUI's AsyncImage cache policy isn't adequate for our use, which means we're hitting the network too much. Let's write our own CachedAsyncImage view that will...
- Fetch images given a url
- Save images to the documents directory
- Load images from the documents directory
- Act as a drop in replacement for AsyncImage
For now we'll just implement Step 2 and 3.
- Dramatically decrease network traffic
- Local image storage for future features
extension FileManager {
static var getDocumentsDirectory: URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
}
extension UIImage {
func saveJPG(named: String) {
if let data = self.jpegData(compressionQuality: 1.0) {
let filename = FileManager.getDocumentsDirectory.appendingPathComponent("\(named)")
log("🗃 \(filename)")
try? data.write(to: filename)
}
}
}
extension FileManager {
private func loadImage(name: String) -> UIImage? {
let filename = FileManager.getDocumentsDirectory.appendingPathComponent("\(name)")
let image = UIImage(contentsOfFile: filename.path)
log("🗃 \(filename)")
return image
}
}