From eb8107dc8913f58e576fbae777176f0905cfca0e Mon Sep 17 00:00:00 2001 From: Kevin Wolkober Date: Mon, 13 Jun 2016 18:40:46 +0800 Subject: [PATCH] Add cache get/set with URL request/response --- SKPhotoBrowser/SKCachable.swift | 10 +++++++++- SKPhotoBrowser/SKCache.swift | 24 ++++++++++++++++++------ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/SKPhotoBrowser/SKCachable.swift b/SKPhotoBrowser/SKCachable.swift index 16cfa84..3287667 100644 --- a/SKPhotoBrowser/SKCachable.swift +++ b/SKPhotoBrowser/SKCachable.swift @@ -8,8 +8,16 @@ import UIKit.UIImage -public protocol SKCacheable { +public protocol SKImageCacheable: SKCacheable { func imageForKey(key: String) -> UIImage? func setImage(image: UIImage, forKey key: String) func removeImageForKey(key: String) +} + +public protocol SKRequestResponseCacheable: SKCacheable { + func cachedResponseForRequest(request: NSURLRequest) -> NSCachedURLResponse + func storeCachedResponse(cachedResponse: NSCachedURLResponse, forRequest request: NSURLRequest) +} + +public protocol SKCacheable { } \ No newline at end of file diff --git a/SKPhotoBrowser/SKCache.swift b/SKPhotoBrowser/SKCache.swift index b94ee48..f27cda1 100644 --- a/SKPhotoBrowser/SKCache.swift +++ b/SKPhotoBrowser/SKCache.swift @@ -10,27 +10,39 @@ import UIKit public class SKCache { - static let sharedCache = SKCache() - var imageCache: SKCacheable + public static let sharedCache = SKCache() + public var imageCache: SKCacheable init() { self.imageCache = SKDefaultImageCache() } public func imageForKey(key: String) -> UIImage? { - return self.imageCache.imageForKey(key) + return (self.imageCache as! SKImageCacheable).imageForKey(key) } public func setImage(image: UIImage, forKey key: String) { - self.imageCache.setImage(image, forKey: key) + (self.imageCache as! SKImageCacheable).setImage(image, forKey: key) } public func removeImageForKey(key: String) { - self.imageCache.removeImageForKey(key) + (self.imageCache as! SKImageCacheable).removeImageForKey(key) + } + + public func imageForRequest(request: NSURLRequest) -> UIImage? { + let response = (self.imageCache as! SKRequestResponseCacheable).cachedResponseForRequest(request) + let data = response.data + + return UIImage(data: data) + } + + public func setImageData(data: NSData, response: NSURLResponse, request: NSURLRequest) { + let cachedResponse = NSCachedURLResponse(response: response, data: data) + (self.imageCache as! SKRequestResponseCacheable).storeCachedResponse(cachedResponse, forRequest: request) } } -class SKDefaultImageCache: SKCacheable { +class SKDefaultImageCache: SKImageCacheable { var cache: NSCache init() {