init, finished

This commit is contained in:
Joshua Higgins
2025-06-02 17:49:33 -04:00
parent bbc0606bab
commit 4ef60608cd
16 changed files with 1550 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
import Foundation
class GIFStorageService {
static let shared = GIFStorageService()
private let userDefaults = UserDefaults(suiteName: "group.gifcollector")
private let savedGIFsKey = "savedGIFs"
private init() {
// Make sure the shared UserDefaults exists
if userDefaults == nil {
print("Error: Could not create UserDefaults with app group")
}
}
func saveGIF(_ gif: GIF) {
var savedGIFs = fetchGIFs()
// Don't save duplicate URLs
if !savedGIFs.contains(where: { $0.urlString == gif.urlString }) {
savedGIFs.append(gif)
saveToUserDefaults(gifs: savedGIFs)
}
}
func fetchGIFs() -> [GIF] {
guard let data = userDefaults?.data(forKey: savedGIFsKey),
let gifs = try? JSONDecoder().decode([GIF].self, from: data) else {
return []
}
return gifs.sorted(by: { $0.createdAt > $1.createdAt })
}
func deleteGIF(with id: UUID) {
var savedGIFs = fetchGIFs()
savedGIFs.removeAll(where: { $0.id == id })
saveToUserDefaults(gifs: savedGIFs)
}
func clearAllGIFs() {
saveToUserDefaults(gifs: [])
}
private func saveToUserDefaults(gifs: [GIF]) {
guard let data = try? JSONEncoder().encode(gifs) else { return }
userDefaults?.set(data, forKey: savedGIFsKey)
}
}