Skip to content

Commit

Permalink
Merge pull request #7 from d4r1091/fix/configure-func-and-request
Browse files Browse the repository at this point in the history
Various improvements
  • Loading branch information
Sadmansamee committed Sep 1, 2020
2 parents fed25ba + 155ea47 commit 889fede
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 36 deletions.
2 changes: 1 addition & 1 deletion Example/CachyDemo/BoardCell.swift
Expand Up @@ -23,7 +23,7 @@ class BoardCell: UICollectionViewCell {
didSet {
if let board = board, let urls = board.urls, let thumb = urls.regular, let url = URL(string: thumb) {
let request = URLRequest(url: url)
cachy.loadWith(urlRequest: request) { [weak self] data, _ in
cachy.loadWithURLRequest(request) { [weak self] data, _ in
self?.imageView.image = UIImage(data: data, scale: 1.0)
}
// imageView.cachyImageLoad(url, isShowLoading: true, completionBlock: { _, _ in })
Expand Down
5 changes: 3 additions & 2 deletions Example/CachyDemo/ViewController.swift
Expand Up @@ -35,8 +35,9 @@ class ViewController: UICollectionViewController {
}

private func fetchData(isRefresh _: Bool = false) {
let url = URLRequest(url: URL(string: Constant.Url.base)!)
cachy.loadWith(urlRequest: url) { [weak self] data, _ in
CachyLoaderManager.shared.configure(isOnlyInMemory: false)
let request = URLRequest(url: URL(string: Constant.Url.base)!)
cachy.loadWithURLRequest(request) { [weak self] data, _ in
let decoder = JSONDecoder()
do {
guard let self = self else {
Expand Down
12 changes: 7 additions & 5 deletions README.md
Expand Up @@ -53,7 +53,7 @@ If you want to download and cache a file(JSON, ZIP, UIImage or any type) then si
```swift
let cachy = CachyLoader()

cachy.load(url: URL(string: "http://your_url_here")!) { [weak self] data, _ in
cachy.loadWithURL(URL(string: "http://your_url_here")!) { [weak self] data, _ in
// Do whatever you need with the data object
}
```
Expand All @@ -63,8 +63,8 @@ You can also cache with **URLRequest**
```swift
let cachy = CachyLoader()

let url = URLRequest(url: URL(string: "http://your_url_here")!)
cachy.loadWith(urlRequest: url) { [weak self] data, _ in
let request = URLRequest(url: URL(string: "http://your_url_here")!)
cachy.loadWithURLRequest(request) { [weak self] data, _ in
// Do whatever you need with the data object
}
```
Expand All @@ -77,7 +77,7 @@ let cachy = CachyLoader()
//(optional) if isRefresh = true it will forcefully refresh data from remote server
//(optional) you can set **expirationDate** according to your need

cachy.load(url: URL(string: "http://your_url_here")!,isRefresh = false,expirationDate = ExpiryDate.everyDay.expiryDate()) { [weak self] data, _ in
cachy.loadWithURL(URL(string: "http://your_url_here")!,isRefresh = false,expirationDate = ExpiryDate.everyDay.expiryDate()) { [weak self] data, _ in
// Do whatever you need with the data object
}
```
Expand All @@ -99,13 +99,15 @@ It will download, cache and load UIImage into your UIImageView
// Here if you want set how much much memory/disk should use set memoryCapacity, diskCapacity
// To cache only on memory set isOnlyInMemory which is true by default
// You may set expiry date for all the cache object by setting expiryDate
// Your objects may not be conforming to `NSSecureCoding`, set this variable to `false`

CachyLoaderManager.shared.configure(
memoryCapacity: 1020,
maxConcurrentOperationCount: 10,
timeoutIntervalForRequest: 3,
expiryDate: ExpiryDate.everyWeek,
isOnlyInMemory: true
isOnlyInMemory: true,
isSupportingSecureCodingSaving: false
)
```

Expand Down
7 changes: 5 additions & 2 deletions Sources/Cachy/Cachy.swift
Expand Up @@ -71,7 +71,11 @@ public class Cachy: NSCache<AnyObject, AnyObject> {
/// 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 = true

/// For those objects not conforming to `NSSecureCoding`, set this variable to `false`
public static var isSupportingSecureCodingSaving = true

// MARK: - Public properties

Expand Down Expand Up @@ -269,9 +273,8 @@ public class Cachy: NSCache<AnyObject, AnyObject> {
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: true)
let data = try? NSKeyedArchiver.archivedData(withRootObject: object, requiringSecureCoding: Cachy.isSupportingSecureCodingSaving)
try? data?.write(to: fileName)
} else {
let data = try? NSKeyedArchiver.archivedData(withRootObject: object)
Expand Down
65 changes: 40 additions & 25 deletions Sources/Cachy/CachyLoader.swift
Expand Up @@ -18,7 +18,7 @@ open class CachyLoaderManager {
let instance = CachyLoaderManager()
return instance
}()

fileprivate var cache: Cachy
private var fetchList: [String: CachyCallbackList] = [:]
private var fetchListOperationQueue: DispatchQueue = DispatchQueue(label: "cachy.awesome.fetchlist_queue",
Expand All @@ -27,25 +27,28 @@ open class CachyLoaderManager {
private var sessionQueue: OperationQueue!
fileprivate lazy var defaultSession: URLSession! = URLSession(configuration:
self.sessionConfiguration, delegate: nil,
delegateQueue: self.sessionQueue)

func configure(memoryCapacity: Int = 30 * 1024 * 1024,
maxConcurrentOperationCount: Int = 10,
timeoutIntervalForRequest: Double = 3,
expiryDate: ExpiryDate = .everyWeek,
isOnlyInMemory: Bool = true) {
delegateQueue: self.sessionQueue)

public func configure(memoryCapacity: Int = 30 * 1024 * 1024,
maxConcurrentOperationCount: Int = 10,
timeoutIntervalForRequest: Double = 3,
expiryDate: ExpiryDate = .everyWeek,
isOnlyInMemory: Bool = true,
isSupportingSecureCodingSaving: Bool = true) {
cache.totalCostLimit = memoryCapacity
cache.expiration = expiryDate

Cachy.isOnlyInMemory = isOnlyInMemory

Cachy.isSupportingSecureCodingSaving = isSupportingSecureCodingSaving

sessionQueue = OperationQueue()
sessionQueue.maxConcurrentOperationCount = maxConcurrentOperationCount
sessionQueue.name = "cachy.awesome.session"
sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.requestCachePolicy = .useProtocolCachePolicy
sessionConfiguration.timeoutIntervalForRequest = timeoutIntervalForRequest
}

private init(memoryCapacity: Int = 30 * 1024 * 1024,
maxConcurrentOperationCount: Int = 10,
timeoutIntervalForRequest: Double = 3,
Expand All @@ -62,7 +65,7 @@ extension CachyLoaderManager {
fileprivate func readFetch(_ key: String) -> CachyCallbackList? {
return fetchList[key]
}

fileprivate func addFetch(_ key: String, callback: @escaping CachyCallback) -> Bool {
var skip = false
let list = fetchList[key]
Expand All @@ -79,13 +82,13 @@ extension CachyLoaderManager {
})
return skip
}

fileprivate func removeFetch(_ key: String) {
_ = fetchListOperationQueue.sync(flags: .barrier) {
self.fetchList.removeValue(forKey: key)
}
}

fileprivate func clearFetch() {
fetchListOperationQueue.async(flags: .barrier) {
self.fetchList.removeAll()
Expand Down Expand Up @@ -115,29 +118,41 @@ extension CachyLoader {
let cacheKey = path
return cacheKey
}

fileprivate func dataFromFastCache(cacheKey: String) -> Data? {
return CachyLoaderManager.shared.cache.get(forKey: cacheKey)
// return CachyLoaderManager.shared.cache.object(forKey: cacheKey as NSString) as? Data
}

public func loadWith(urlRequest: URLRequest,
isRefresh: Bool = false,
expirationDate: Date? = nil,
callback: @escaping CachyCallback) {
public func loadWithURLRequest(_ urlRequest: URLRequest,
isRefresh: Bool = false,
expirationDate: Date? = nil,
callback: @escaping CachyCallback) {
guard let url = urlRequest.url else {
return
}
load(url: url,
urlRequest: urlRequest,
isRefresh: isRefresh,
expirationDate: expirationDate,
callback: callback)
}

public func load(url: URL,
isRefresh: Bool = false,
expirationDate: Date? = nil,
callback: @escaping CachyCallback) {

public func loadWithURL(_ url: URL,
isRefresh: Bool = false,
expirationDate: Date? = nil,
callback: @escaping CachyCallback) {
load(url: url,
isRefresh: isRefresh,
expirationDate: expirationDate,
callback: callback)
}

private func load(url: URL,
urlRequest: URLRequest? = nil,
isRefresh: Bool = false,
expirationDate: Date? = nil,
callback: @escaping CachyCallback) {
guard let fetchKey = self.cacheKeyFromUrl(url: url as URL) else {
return
}
Expand All @@ -163,7 +178,7 @@ extension CachyLoader {
return
}
let session = CachyLoaderManager.shared.defaultSession
let request = URLRequest(url: url)
let request = urlRequest ?? URLRequest(url: url)
task = session?.dataTask(with: request, completionHandler: { data, _, _ in
guard let data = data else {
return
Expand Down
2 changes: 1 addition & 1 deletion Sources/Cachy/CachyUIImage.swift
Expand Up @@ -78,7 +78,7 @@ public extension UIImageView {
showLoading()
}
let loader = CachyLoader()
loader.load(url: url) { [weak self] data, url in
loader.loadWithURL(url) { [weak self] data, url in
if isShowLoading {
self?.hideLoading()
}
Expand Down

0 comments on commit 889fede

Please sign in to comment.