Save GIFs Locally

This commit is contained in:
Joshua Higgins
2025-06-03 22:18:23 -04:00
parent a09e08763f
commit 8ce5adc766
8 changed files with 283 additions and 116 deletions

View File

@@ -13,14 +13,28 @@ class GIFStorageService {
}
}
func saveGIF(_ gif: GIF) {
func saveGIF(data: Data, fromURL urlString: String, completion: @escaping (GIF?) -> Void) {
// First store the GIF data to disk
guard let localPath = GIFFileManager.shared.storeGIF(data: data, fromURL: urlString) else {
completion(nil)
return
}
// Create and save the GIF model
let gif = GIF(localFilePath: localPath, originalURL: urlString)
var savedGIFs = fetchGIFs()
// Don't save duplicate URLs
if !savedGIFs.contains(where: { $0.urlString == gif.urlString }) {
// Don't save duplicates of the same URL
if !savedGIFs.contains(where: { $0.originalURL == urlString }) {
savedGIFs.append(gif)
saveToUserDefaults(gifs: savedGIFs)
}
// Perform cleanup if needed
GIFFileManager.shared.performStorageCleanupIfNeeded()
completion(gif)
}
func fetchGIFs() -> [GIF] {
@@ -29,16 +43,38 @@ class GIFStorageService {
return []
}
return gifs.sorted(by: { $0.createdAt > $1.createdAt })
// Filter out any GIFs whose files no longer exist
let validGIFs = gifs.filter { GIFFileManager.shared.fileExists(at: $0.localFilePath) }
// If we filtered any out, save the updated list
if validGIFs.count != gifs.count {
saveToUserDefaults(gifs: validGIFs)
}
return validGIFs.sorted(by: { $0.createdAt > $1.createdAt })
}
func deleteGIF(with id: UUID) {
var savedGIFs = fetchGIFs()
savedGIFs.removeAll(where: { $0.id == id })
saveToUserDefaults(gifs: savedGIFs)
// Find the GIF to delete
if let gifToDelete = savedGIFs.first(where: { $0.id == id }) {
// Delete the file from storage
GIFFileManager.shared.deleteGIF(at: gifToDelete.localFilePath)
// Remove from the list
savedGIFs.removeAll(where: { $0.id == id })
saveToUserDefaults(gifs: savedGIFs)
}
}
func clearAllGIFs() {
// Delete all GIF files
fetchGIFs().forEach { gif in
GIFFileManager.shared.deleteGIF(at: gif.localFilePath)
}
// Clear the list
saveToUserDefaults(gifs: [])
}
@@ -46,4 +82,8 @@ class GIFStorageService {
guard let data = try? JSONEncoder().encode(gifs) else { return }
userDefaults?.set(data, forKey: savedGIFsKey)
}
func getGIFData(for gif: GIF) -> Data? {
return GIFFileManager.shared.loadGIFData(from: gif.localFilePath)
}
}