This is a simple disk and memory cache for iOS and macOS written in Swift. It can cache Codable
types, NSCoding
types, primitive types (String
, Int
, Array
, etc.).
There are some reasons why you would like to use this libary for caching:
Add below lines to your Podfile:
pod 'DataCache'
Note: If above pod doesn't work, try using the below pod defination in Podfile:
pod 'DataCache', :git => 'https://github.com/huynguyencong/DataCache.git'
In Xcode, select menu File -> Swift Packages -> Add Package Dependency. Select a target, then add this link to the input field:
https://github.com/huynguyencong/DataCache.git
Add all files in the Sources
folder to your project.
Use default cache a create new cache if you want. In each cache instance, you can setup cache size and expired time.
Cache Codable
types, include your custom types that conformed to Codable
protocol, and primitive types (String
, Int
, etc.) which have already conformed to Codable
by default.
do {
try DataCache.instance.write(codable: myCodableObject, forKey: "myKey")
} catch {
print("Write error \(error.localizedDescription)")
}
do {
let object: MyCodableObject? = try DataCache.instance.readCodable(forKey: "myKey")
} catch {
print("Read error \(error.localizedDescription)")
}
UIImage
or NSImage
// on iOS
let image = UIImage(named: "myImageName")
// on macOS
let image = NSImage(named: "myImageName")
// will be written in a same way
DataCache.instance.write(image: image!, forKey: "imageKey")
let image = DataCache.instance.readImage(forKey: "imageKey")
Data
let data = ... // your data
DataCache.instance.write(data: data, forKey: "myKey")
let data = DataCache.instance.readData(forKey: "myKey")
You can clean by key, or clean all, use one of below methods:
DataCache.instance.clean(byKey: "myKey")
DataCache.instance.cleanAll()
It also clear cache after expiration day. The Default expiration day is 1 week. If you want to customize expiration, please create your customized cache by below instruction.
Just make your type conform to Codable.
struct User: Codable {
let name: String
let yearOld: Double
}
Beside using default cache DataCache.instance
, you can create your cache instances, then you can set different expiration time, disk size, disk path. The name parameter specifies path name for disk cache.
let cache = DataCache(name: "MyCustomCache")
cache.maxDiskCacheSize = 100*1024*1024 // 100 MB
cache.maxCachePeriodInSecond = 7*86400 // 1 week
This open source use some piece of code from Kingfisher library.
DataCache is released under the MIT license. See LICENSE for details. Copyright © Nguyen Cong Huy
link |
Stars: 97 |
Last commit: 13 weeks ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics