-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathURLAssetCache.swift
More file actions
71 lines (59 loc) · 1.85 KB
/
URLAssetCache.swift
File metadata and controls
71 lines (59 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import Foundation
import CryptoKit
enum URLAssetCache {
private static let cacheDirName = "rive_url_assets"
private static func getCacheDirectory() -> URL? {
guard let cacheDir = FileManager.default.urls(
for: .cachesDirectory,
in: .userDomainMask
).first else {
return nil
}
let riveCacheDir = cacheDir.appendingPathComponent(cacheDirName)
// Create directory if it doesn't exist
try? FileManager.default.createDirectory(
at: riveCacheDir,
withIntermediateDirectories: true,
attributes: nil
)
return riveCacheDir
}
private static func urlToCacheKey(_ url: String) -> String {
let data = Data(url.utf8)
let hash = SHA256.hash(data: data)
return hash.compactMap { String(format: "%02x", $0) }.joined()
}
private static func getCacheFileURL(for url: String) -> URL? {
guard let cacheDir = getCacheDirectory() else { return nil }
let cacheKey = urlToCacheKey(url)
return cacheDir.appendingPathComponent(cacheKey)
}
static func getCachedData(for url: String) -> Data? {
guard let cacheFileURL = getCacheFileURL(for: url) else { return nil }
do {
let data = try Data(contentsOf: cacheFileURL)
return data.isEmpty ? nil : data
} catch {
return nil
}
}
static func saveToCache(_ data: Data, for url: String) {
guard let cacheFileURL = getCacheFileURL(for: url) else { return }
do {
try data.write(to: cacheFileURL)
} catch {
// Silently fail - caching is best effort
}
}
static func clearCache() {
guard let cacheDir = getCacheDirectory() else { return }
do {
let files = try FileManager.default.contentsOfDirectory(at: cacheDir, includingPropertiesForKeys: nil)
for file in files {
try? FileManager.default.removeItem(at: file)
}
} catch {
// Silently fail
}
}
}