HistoryManager.swift

1.0 KB · raw

1import Foundation23class HistoryManager: ObservableObject {4  static let shared = HistoryManager()56  @Published var history: [Wallpaper] = []7  private let key = "wallpaperHistory"8  private let maxHistoryItems = 50910  init() {11    loadHistory()12  }1314  func addToHistory(_ wallpaper: Wallpaper) {15    // Remove if existing to promote to top16    if let index = history.firstIndex(where: { $0.id == wallpaper.id }) {17      history.remove(at: index)18    }1920    history.insert(wallpaper, at: 0)2122    if history.count > maxHistoryItems {23      history = Array(history.prefix(maxHistoryItems))24    }2526    saveHistory()27  }2829  func clearHistory() {30    history = []31    saveHistory()32  }3334  private func saveHistory() {35    if let data = try? JSONEncoder().encode(history) {36      UserDefaults.standard.set(data, forKey: key)37    }38  }3940  private func loadHistory() {41    if let data = UserDefaults.standard.data(forKey: key),42      let decoded = try? JSONDecoder().decode([Wallpaper].self, from: data)43    {44      history = decoded45    }46  }47}