Digital PCT265 story MVAPCT-48 - Caches root directory, file protection for encryption, atomicWrite API deprecation.

This commit is contained in:
Hedden, Kyle Matthew 2024-03-29 16:45:23 -04:00
parent 4fc4aa21f3
commit d08a8f6782

View File

@ -49,7 +49,7 @@ public class CachedData: Codable {
@objc public class PersistentCacheManager: NSObject {
@objc public static let shared = PersistentCacheManager()
private let fileManager = FileManager.default
private lazy var documentsDirectory = { fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! }()
private lazy var cacheDirectory = { fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("Atomic")}()
private override init() {}
@ -57,8 +57,9 @@ public class CachedData: Codable {
let cachedData = CachedData(data: data, expirationDate: expirationDate)
let filePath = self.filePath(forKey: key)
do {
try FileManager.default.createDirectory(atPath: self.cacheDirectory.relativePath, withIntermediateDirectories: true, attributes: [.protectionKey: FileProtectionType.complete])
let dataToSave = try JSONEncoder().encode(cachedData)
try dataToSave.write(to: filePath, options: .atomicWrite)
try dataToSave.write(to: filePath, options: [.atomic, .completeFileProtection])
} catch is EncodingError {
throw CacheError.serializationFailed
} catch {
@ -97,16 +98,18 @@ public class CachedData: Codable {
}
@objc public func removeAll() throws {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsDirectory,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles)
let fileURLs = try fileManager.contentsOfDirectory(
at: cacheDirectory,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles
)
for fileURL in fileURLs where fileURL.pathExtension == "json" {
try FileManager.default.removeItem(at: fileURL)
}
}
private func filePath(forKey key: String) -> URL {
return documentsDirectory.appendingPathComponent("\(key).json")
return cacheDirectory.appendingPathComponent("\(key).json")
}
}