1import Foundation23class HistoryManager: ObservableObject {4 static let shared = HistoryManager()5 6 @Published var history: [Wallpaper] = []7 private let key = "wallpaperHistory"8 private let maxHistoryItems = 509 10 init() {11 loadHistory()12 }13 14 func addToHistory(_ wallpaper: Wallpaper) {15 16 if let index = history.firstIndex(where: { $0.id == wallpaper.id }) {17 history.remove(at: index)18 }19 20 history.insert(wallpaper, at: 0)21 22 if history.count > maxHistoryItems {23 history = Array(history.prefix(maxHistoryItems))24 }25 26 saveHistory()27 }28 29 func clearHistory() {30 history = []31 saveHistory()32 }33 34 private func saveHistory() {35 if let data = try? JSONEncoder().encode(history) {36 UserDefaults.standard.set(data, forKey: key)37 }38 }39 40 private func loadHistory() {41 if let data = UserDefaults.standard.data(forKey: key),42 let decoded = try? JSONDecoder().decode([Wallpaper].self, from: data) {43 history = decoded44 }45 }46}