数据缓存可以简单将数据缓存到沙盒,结合RSA或者其他加密,可以将数据安全地缓存在本地,而不用操作较为复杂的数据库。
demo
enum CacheManagerPath {
case demoCache
case none
var directory: String {
if case . demoCache = self {
return "demoCache"
}
return ""
}
var path: String {
if case . demoCache = self {
return "userId.txt"
}
return ""
}
}
protocol CacheManagerProtocol {
var filePath: CacheManagerPath { get }
func write(_ data: Data?) throws
func read<T: Codable>() throws -> T
func remove()
}
extension CacheManagerProtocol {
func write(_ data: Data?) {
do {
let fileUrl = try fileUrl(by: filePath.path)
try createDirectories(in: fileUrl.deletingLastPathComponent())
if let data = data {
try data.write(to: fileUrl, option: .atomic)
} else {
let emptyData = Data()
try emptyData.write(to: fileUrl, options: .atomic)
}
} catch {}
}
func read<T: Codable>() throws -> T {
let fileUrl = try fileUrl(by: filePath.path)
let data = try Data(contentsOf: fileUrl)
return try JSONDecoder().decode(T.self, from: data)
}
func remove() {
// remove all the directory
do {
let fileUrl = try fileUrl(by: filePath.directory)
try FileManager.default.removeItem(at: fileUrl)
} catch {}
}
private func createDirectories(in url: URL) throws {
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
} catch {}
}
private func fileUrl(by fileName: String) throws -> URL {
return try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(fileName)
}
}
class CacheManager: CacheManagerProtocol {
var filePath: CacheManagerPath
init(filePath: CacheManagerPath) {
self.filePath = filePath
}
}
protocol TestDemoProtocol {
var localStore: CacheManager { get }
func saveToCache(response: Sample)
...
}
class TestDemo: TestDemoProtocol {
init(localStore: CacheManager = CacheManager(filePath: . demoCache)) {
self. localStore = localStore
}
func saveToCache(response: Sample) {
let data = try JSONEncoder().encode(response)
try localStore.write(data)
}
}