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

@@ -1,19 +1,19 @@
import Foundation
import UIKit
class GIFDownloadService {
static let shared = GIFDownloadService()
class DownloadService {
static let shared = DownloadService()
private let cache = NSCache<NSString, NSData>()
private var activeTasks: [URL: URLSessionDataTask] = [:]
private init() {
cache.totalCostLimit = 100 * 1024 * 1024 // 100 MB cache limit
cache.totalCostLimit = 50 * 1024 * 1024 // 50 MB cache limit
}
func downloadGIF(from urlString: String, completion: @escaping (Data?, Error?) -> Void) {
guard let url = URL(string: urlString) else {
completion(nil, NSError(domain: "GIFDownloadService", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"]))
completion(nil, NSError(domain: "DownloadService", code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"]))
return
}
@@ -35,7 +35,7 @@ class GIFDownloadService {
guard let self = self, error == nil, let data = data else {
DispatchQueue.main.async {
completion(nil, error ?? NSError(domain: "GIFDownloadService", code: 2, userInfo: [NSLocalizedDescriptionKey: "Failed to download GIF"]))
completion(nil, error ?? NSError(domain: "DownloadService", code: 2, userInfo: [NSLocalizedDescriptionKey: "Failed to download GIF"]))
}
return
}

View File

@@ -0,0 +1,132 @@
import Foundation
import UIKit
class GIFFileManager {
static let shared = GIFFileManager()
private init() {
createGIFsDirectoryIfNeeded()
}
// MARK: - File Storage
private var documentsDirectory: URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
private var gifsDirectory: URL {
return documentsDirectory.appendingPathComponent("SavedGIFs", isDirectory: true)
}
private func createGIFsDirectoryIfNeeded() {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: gifsDirectory.path) {
do {
try fileManager.createDirectory(at: gifsDirectory, withIntermediateDirectories: true)
} catch {
print("Error creating GIFs directory: \(error)")
}
}
}
func storeGIF(data: Data, fromURL urlString: String) -> String? {
// Create a unique filename based on the URL hash and timestamp
let urlHash = urlString.hashValue
let timestamp = Int(Date().timeIntervalSince1970)
let filename = "gif_\(urlHash)_\(timestamp).gif"
let fileURL = gifsDirectory.appendingPathComponent(filename)
do {
try data.write(to: fileURL)
return fileURL.path
} catch {
print("Error saving GIF to disk: \(error)")
return nil
}
}
func loadGIFData(from localPath: String) -> Data? {
let url = URL(fileURLWithPath: localPath)
do {
let data = try Data(contentsOf: url)
return data
} catch {
print("Error loading GIF from disk: \(error)")
return nil
}
}
func deleteGIF(at localPath: String) -> Bool {
let fileManager = FileManager.default
do {
try fileManager.removeItem(atPath: localPath)
return true
} catch {
print("Error deleting GIF from disk: \(error)")
return false
}
}
func fileExists(at localPath: String) -> Bool {
return FileManager.default.fileExists(atPath: localPath)
}
func getAllGIFsSize() -> Int64 {
let fileManager = FileManager.default
let enumerator = fileManager.enumerator(at: gifsDirectory, includingPropertiesForKeys: [.fileSizeKey])
var totalSize: Int64 = 0
while let fileURL = enumerator?.nextObject() as? URL {
do {
let attributes = try fileURL.resourceValues(forKeys: [.fileSizeKey])
if let fileSize = attributes.fileSize {
totalSize += Int64(fileSize)
}
} catch {
print("Error calculating file size: \(error)")
}
}
return totalSize
}
// Clean up old GIFs if storage exceeds 100 MB
func performStorageCleanupIfNeeded() {
let maxStorageSize: Int64 = 100 * 1024 * 1024 // 100 MB
if getAllGIFsSize() > maxStorageSize {
cleanupOldGIFs()
}
}
private func cleanupOldGIFs() {
let fileManager = FileManager.default
do {
// Get all files and their creation dates
let fileURLs = try fileManager.contentsOfDirectory(at: gifsDirectory, includingPropertiesForKeys: [.creationDateKey])
// Sort by creation date
let sortedFiles = try fileURLs.sorted {
let date1 = try $0.resourceValues(forKeys: [.creationDateKey]).creationDate ?? Date.distantPast
let date2 = try $1.resourceValues(forKeys: [.creationDateKey]).creationDate ?? Date.distantPast
return date1 < date2
}
// Delete the oldest 30% of files
let filesToDelete = Int(Double(sortedFiles.count) * 0.3)
for i in 0..<min(filesToDelete, sortedFiles.count) {
try fileManager.removeItem(at: sortedFiles[i])
}
} catch {
print("Error cleaning up old GIFs: \(error)")
}
}
}

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)
}
}