-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathCachy.swift
executable file
·294 lines (232 loc) · 10.1 KB
/
Cachy.swift
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import UIKit
public enum Operations: Swift.Error {
case fetchFail
case deleteFail
case saveFail
case loadFail
case folderCreation
}
public enum ExpiryDate {
case never
case everyDay
case everyWeek
case everyMonth
case seconds(TimeInterval)
public var date: Date {
switch self {
case .never:
return Date.distantFuture
case .everyDay:
return endOfDay
case .everyWeek:
return date(afterDays: 7)
case .everyMonth:
return date(afterDays: 30)
case let .seconds(seconds):
return Date().addingTimeInterval(seconds)
}
}
private func date(afterDays days: Int) -> Date {
return Calendar.current.date(byAdding: .day, value: days, to: Date()) ?? Date()
}
private var endOfDay: Date {
let startOfDay = Calendar.current.startOfDay(for: Date())
var components = DateComponents()
components.day = 1
components.second = -1
return Calendar.current.date(byAdding: components, to: startOfDay) ?? Date()
}
}
public class Cachy: NSCache<AnyObject, AnyObject> {
public static var shared: Cachy {
struct Static {
static var instance = Cachy() {
didSet {
Static.instance.countLimit = Cachy.countLimit
Static.instance.totalCostLimit = Cachy.totalCostLimit
}
}
}
return Static.instance
}
// MARK: - Static properties
/// Static property to store the count of element stored in the cache (by default it is 100)
public static var countLimit = 100
/// Static property to store the cost limit of the cache (by default it is 0)
public static var totalCostLimit = 0
/// Caching only on memory, otherwise will try to cache to Disk too
public static var isOnlyInMemory = false
/// For those objects not conforming to `NSSecureCoding`, set this variable to `false`
public static var isSupportingSecureCodingSaving = true
// MARK: - Public properties
/// Public property to store the expiration date of each object in the cache (by default it is set to .never)
open var expiration: ExpiryDate = .never
// MARK: - Public methods
/// Public method to add an object to the cache
///
/// - Parameter object: The object which will be added to the cache
open func add(object: CachyObject) {
var objects = self.object(forKey: cacheKey as AnyObject) as? [CachyObject]
if objects?.contains(where: { $0.key == object.key }) == false {
objects?.append(object)
set(object: objects as AnyObject)
} else {
update(object: object)
}
if !Cachy.isOnlyInMemory {
try? save(object: object)
}
}
open func get<T>(forKey key: String) -> T? {
let objects = object(forKey: cacheKey as AnyObject) as? [CachyObject]
let objectsOfType = objects?.filter { $0.value is T }
return objectsOfType?.filter { $0.key == key }.first?.value as? T
}
open func update(object: CachyObject) {
var objects = self.object(forKey: cacheKey as AnyObject) as? [CachyObject]
if let index = objects?.firstIndex(where: { $0.key == object.key }) {
objects?.remove(at: index)
objects?.append(object)
}
set(object: objects as AnyObject)
}
///
@available(*, deprecated, message: "")
open func save() throws {
let objects = object(forKey: cacheKey as AnyObject) as? [CachyObject] ?? [CachyObject]()
let fileManager = FileManager.default
do {
let cacheDirectory = try fileManager.url(for: .cachesDirectory,
in: .allDomainsMask,
appropriateFor: nil,
create: false)
let fileDirectory = cacheDirectory.appendingPathComponent("cachykit")
var fileDir = fileDirectory.absoluteString
let range = fileDir.startIndex ..< fileDir.index(fileDir.startIndex, offsetBy: 7)
fileDir.removeSubrange(range)
try createFolderIfRequires(atPath: fileDir, absolutePath: fileDirectory)
for object in objects {
let fileFormatedName = object.key.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? object.key
let fileName = fileDirectory.appendingPathComponent(fileFormatedName)
let data = NSKeyedArchiver.archivedData(withRootObject: object)
try? data.write(to: fileName)
}
set(object: objects as AnyObject)
} catch {
throw Operations.saveFail
}
}
// MARK: - Initialize/Livecycle methods
override init() {
super.init()
loadCache()
NotificationCenter.default.addObserver(self, selector: #selector(activatingApplication(notification:)), name: UIApplication.willEnterForegroundNotification, object: nil)
}
// MARK: - Override methods
// MARK: - Private properties
/// read only private property to store the identifier of the read/write queue
private let cacheKey = Bundle.main.bundleIdentifier ?? ""
/// private property to store a lock for conqurency
private let lock = NSLock()
// MARK: - Private methods
/// Private method to create the cache folder if it doesn't exist
///
/// - Parameter path: The path where the folder will be created
private func createFolderIfRequires(atPath path: String, absolutePath: URL) throws {
let fileManager = FileManager.default
var isDirectory: ObjCBool = false
do {
if !fileManager.fileExists(atPath: path, isDirectory: &isDirectory) {
try fileManager.createDirectory(at: absolutePath, withIntermediateDirectories: false, attributes: nil)
}
} catch {
throw Operations.folderCreation
}
}
/// Private method to set object to the cache
///
/// - Parameter object: The object to be added to the cache
private func set(object: AnyObject) {
lock.lock()
setObject(object, forKey: cacheKey as AnyObject)
lock.unlock()
}
open func clear() {
self.removeAllObjects()
}
/// Public method to load all object from disk to memory
///
/// - Throws: An error if such occures during load
private func load() throws {
let fileManager = FileManager.default
do {
let cacheDirectory = try fileManager.url(for: .cachesDirectory, in: .allDomainsMask, appropriateFor: nil, create: false)
let fileDirectory = cacheDirectory.appendingPathComponent("cachykit")
var fileDir = fileDirectory.absoluteString
let range = fileDir.startIndex ..< fileDir.index(fileDir.startIndex, offsetBy: 7)
fileDir.removeSubrange(range)
try createFolderIfRequires(atPath: fileDir, absolutePath: fileDirectory)
let paths = try fileManager.contentsOfDirectory(atPath: fileDir)
for path in paths {
if #available(iOS 11.0, *) {
if let nsdata = NSData(contentsOfFile: fileDir + path),
let object = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(Data(referencing: nsdata)) as? CachyObject {
if !object.isExpired {
add(object: object)
} else {
try? fileManager.removeItem(atPath: fileDir + path)
}
}
} else {
if let object = NSKeyedUnarchiver.unarchiveObject(withFile: fileDir + path) as? CachyObject {
if !object.isExpired {
add(object: object)
} else {
try? fileManager.removeItem(atPath: fileDir + path)
}
}
}
}
} catch {
throw Operations.loadFail
}
}
private func save(object: CachyObject) throws {
let fileManager = FileManager.default
do {
let cacheDirectory = try fileManager.url(for: .cachesDirectory, in: .allDomainsMask, appropriateFor: nil, create: false)
let fileDirectory = cacheDirectory.appendingPathComponent("cachykit")
var fileDir = fileDirectory.absoluteString
let range = fileDir.startIndex ..< fileDir.index(fileDir.startIndex, offsetBy: 7)
fileDir.removeSubrange(range)
try createFolderIfRequires(atPath: fileDir, absolutePath: fileDirectory)
let fileFormatedName = object.key.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? object.key
let convertedFileName = convertToBase64(withString: fileFormatedName).suffix(45).map { String($0) }.joined()
let fileName = fileDirectory.appendingPathComponent(convertedFileName)
if !fileManager.fileExists(atPath: fileName.absoluteString) || object.isUpdated {
// let data = NSKeyedArchiver.archivedData(withRootObject: object)
// try? data.write(to: fileName)
if #available(iOS 11.0, *) {
let data = try? NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: Cachy.isSupportingSecureCodingSaving)
try? data?.write(to: fileName)
} else {
let data = NSKeyedArchiver.archivedData(withRootObject: object)
try? data.write(to: fileName)
}
}
} catch {
throw Operations.saveFail
}
}
/// Private method to load the cache
private func loadCache() {
set(object: [CachyObject]() as AnyObject)
try? load()
}
private func convertToBase64(withString: String) -> String {
return Data(withString.utf8).base64EncodedString()
}
@objc private func activatingApplication(notification _: Notification) {
loadCache()
}
}