Created
May 19, 2021 09:35
-
-
Save Polenoso/91ec8be65b2c025543cb8cb710d8a5ff to your computer and use it in GitHub Desktop.
Lottie Cache Medium Post
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
import Lottie // We need it because of the Animation Model | |
protocol LottieFileProviding: AnyObject { | |
func animation(forKey: String) -> Animation? | |
func setAnimationData(_ data: Data, forKey: String) | |
} | |
final class LottieFileProvider: LottieFileProviding { | |
static var shared = LottieFileProvider() | |
private let urlBuilder: LottieFileURLBuilding | |
init(urlBuilder: LottieFileURLBuilding = LottieFileURLBuilder()) { | |
self.urlBuilder = urlBuilder | |
} | |
/// 1 | |
func animation(forKey: String) -> Animation? { | |
do { | |
let path = urlBuilder.buildPath(for: forKey) | |
let data = try Data(contentsOf: path) | |
return try JSONDecoder().decode(Animation.self, from: data) | |
} catch { | |
return nil | |
} | |
} | |
/// 2 | |
func setAnimationData(_ data: Data, forKey: String) { | |
do { | |
let path = urlBuilder.buildPath(for: forKey) | |
let directory = urlBuilder.directory | |
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil) | |
try data.write(to: path) | |
} catch { | |
log(error.localizedDescription) | |
} | |
} | |
/// 3 | |
func clearCache() { | |
do { | |
let url = urlBuilder.directory | |
try FileManager.default.removeItem(at: url) | |
} catch { | |
log(error.localizedDescription) | |
} | |
} | |
} | |
////// URL Builder | |
protocol LottieFileURLBuilding: AnyObject { | |
var directory: URL { get } | |
func buildPath(for key: String) -> URL | |
} | |
final class LottieFileURLBuilder: LottieFileURLBuilding { | |
private enum Constant { | |
static let lottieDirectory = "lottie-animations" | |
} | |
private var filesDirectory: URL { | |
do { | |
return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) | |
} catch { | |
log(error.localizedDescription) | |
} | |
return URL(fileURLWithPath: "files") | |
} | |
lazy var directory: URL = { | |
var url = filesDirectory | |
url.appendPathComponent(Constant.lottieDirectory) | |
return url | |
}() | |
/// 4 | |
func buildPath(for key: String) -> URL { | |
let url = URL(string: key) | |
let fileExtension = url?.pathExtension ?? "json" | |
let fileName = url?.deletingPathExtension().lastPathComponent ?? "" | |
return directory.appendingPathComponent(fileName).appendingPathExtension(fileExtension) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment