Last active
January 14, 2023 19:19
-
-
Save ricardopsantos/e5f96f6baf992f18070918b5a5fd7747 to your computer and use it in GitHub Desktop.
Article_13_G6.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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