Skip to content

Instantly share code, notes, and snippets.

@ricardopsantos
Last active January 14, 2023 19:19
Show Gist options
  • Save ricardopsantos/e5f96f6baf992f18070918b5a5fd7747 to your computer and use it in GitHub Desktop.
Save ricardopsantos/e5f96f6baf992f18070918b5a5fd7747 to your computer and use it in GitHub Desktop.
Article_13_G6.swift
public class SimpleCacheManagerForCodable: CodableCacheManagerProtocol {
private init() {}
public static let shared = SimpleCacheManagerForCodable()
public func syncStore<T: Codable>(_ codable: T,
key: String,
params: [String],
timeToLiveMinutes: Int? = nil) {
let expiringCodableObjectWithKey = ExpiringCodableObjectWithKey(codable,
key: key,
params: params,
timeToLiveMinutes: timeToLiveMinutes)
UserDefaults.standard.set(try? JSONEncoder().encode(expiringCodableObjectWithKey),
forKey: expiringCodableObjectWithKey.key)
}
public func syncRetrieve<T: Codable>(_ type: T.Type, key: String, params: [String]) -> (model: T, recordDate: Date)? {
guard let data = UserDefaults.standard.data(forKey: ExpiringCodableObjectWithKey.composedKey(key, params)),
let expiringCodableObjectWithKey = try? JSONDecoder().decode(ExpiringCodableObjectWithKey.self, from: data),
let cachedRecord = expiringCodableObjectWithKey.extract(type) else {
return nil
}
return (cachedRecord, expiringCodableObjectWithKey.recordDate)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment