block-employee-directory-in.../EmployeeDirectory/Services/EmployeeCacheService.swift
Matt Bruce a6679a56e9 clean up vars
Signed-off-by: Matt Bruce <mbrucedogs@gmail.com>
2025-02-06 15:45:27 -06:00

47 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 {
private lazy var fileURL = cacheDirectory.appendingPathComponent("employees.json")
// 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: fileURL)
}
public func load() throws -> Employees {
let data = try Data(contentsOf: fileURL)
return try JSONDecoder().decode(Employees.self, from: data)
}
public func clear() {
try? FileManager.default.removeItem(at: fileURL)
}
}