diff --git a/StickerSlack/Emoji/Emoji.swift b/StickerSlack/Emoji/Emoji.swift index cc6cbd3..977a3e4 100644 --- a/StickerSlack/Emoji/Emoji.swift +++ b/StickerSlack/Emoji/Emoji.swift @@ -26,13 +26,12 @@ struct Emoji: Codable, Identifiable, Hashable { } var remoteImageURL: URL - var isLocal: Bool = false - var isLocalold: Bool { + var isLocal: Bool { return (try? Data(contentsOf: localImageURL)) != nil } var sticker: MSSticker? { - guard isLocalold else { + guard isLocal else { return nil } return try? MSSticker(contentsOfFileURL: localImageURL, localizedDescription: name) @@ -59,7 +58,6 @@ struct Emoji: Codable, Identifiable, Hashable { self.uiID = id self.name = try container.decode(String.self, forKey: .name) self.remoteImageURL = try container.decode(URL.self, forKey: .remoteImageURL) - self.isLocal = FileManager.default.fileExists(atPath: localImageURLString) } init( @@ -70,7 +68,6 @@ struct Emoji: Codable, Identifiable, Hashable { self.uiID = id self.name = apiEmoji.name self.remoteImageURL = apiEmoji.url - self.isLocal = FileManager.default.fileExists(atPath: localImageURLString) } func downloadImage() async throws -> UIImage { @@ -85,6 +82,7 @@ struct Emoji: Codable, Identifiable, Hashable { func deleteImage() { try? FileManager.default.removeItem(at: localImageURL) + return } @MainActor diff --git a/StickerSlack/EmojiHoarder.swift b/StickerSlack/EmojiHoarder.swift index 53adc70..94d9466 100644 --- a/StickerSlack/EmojiHoarder.swift +++ b/StickerSlack/EmojiHoarder.swift @@ -18,6 +18,7 @@ class EmojiHoarder: ObservableObject { private let decoder = JSONDecoder() @Published var emojis: [Emoji] = [] + @Published var localEmojis: Set = [] @Published var filteredEmojis: [Emoji] = [] @Published var prefix: Int = 100 @@ -29,6 +30,7 @@ class EmojiHoarder: ObservableObject { guard !localOnly else { return } Task.detached { await self.loadRemoteDB() + await self.loadLocalEmojis() } } @@ -52,6 +54,11 @@ class EmojiHoarder: ObservableObject { } } + func loadLocalEmojis() async { + self.localEmojis = Set(self.emojis.filter { $0.isLocal }) + return + } + func storeDB() { try! encoder.encode(emojis).write(to: EmojiHoarder.localEmojiDB) } @@ -76,13 +83,14 @@ class EmojiHoarder: ObservableObject { } } + @concurrent func fetchRemoteDB() async -> [Emoji]? { do { async let (data, _) = try URLSession.shared.data(from: endpoint) decoder.dateDecodingStrategy = .iso8601 let decoded: [SlackResponse] = try decoder.decode([SlackResponse].self, from: await data) try storeDB(data: await data) - return SlackResponse.toEmojis(from: decoded) + return await SlackResponse.toEmojis(from: decoded) } catch { print(error.localizedDescription) return nil