45 lines
1.3 KiB
Swift
45 lines
1.3 KiB
Swift
//
|
|
// EmployeeCacheService.swift
|
|
// EmployeeDirectory
|
|
//
|
|
// Created by Matt Bruce on 2/6/25.
|
|
//
|
|
|
|
import Foundation
|
|
import UIKit
|
|
|
|
/// A service that handles image caching using memory, disk, and network in priority order.
|
|
public class EmployeeCacheService {
|
|
// MARK: - Properties
|
|
public static let shared = EmployeeCacheService() // Default shared instance
|
|
|
|
/// Memory cache for storing images in RAM.
|
|
private let emplyoees: Employees? = nil
|
|
|
|
/// File manager for handling disk operations.
|
|
private let fileManager = FileManager.default
|
|
|
|
/// Directory where cached images are stored on disk.
|
|
private let cacheDirectory: URL = {
|
|
FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
|
|
}()
|
|
|
|
// MARK: - Initializer
|
|
|
|
public init() {}
|
|
|
|
public func save(from employees: Employees) throws {
|
|
let data = try JSONEncoder().encode(employees)
|
|
try data.write(to: cacheDirectory.appendingPathComponent("employees.json"))
|
|
}
|
|
|
|
public func load() throws -> Employees {
|
|
let data = try Data(contentsOf: cacheDirectory.appendingPathComponent("employees.json"))
|
|
return try JSONDecoder().decode(Employees.self, from: data)
|
|
}
|
|
|
|
public func clear() {
|
|
try? FileManager.default.removeItem(at: cacheDirectory.appendingPathComponent("employees.json"))
|
|
}
|
|
}
|