@@ -79,7 +79,7 @@ public extension UIImageView {
7979 return
8080 }
8181
82- if let cachedImage = Downloader . cache. object ( forKey: url as AnyObject ) as? UIImage {
82+ if let cachedImage = Downloader . cache. getImage ( forKey: url. absoluteString ) {
8383 handleSuccess ( cachedImage, url)
8484 return
8585 }
@@ -98,7 +98,7 @@ public extension UIImageView {
9898
9999 DispatchQueue . main. async {
100100 if response? . url == url {
101- Downloader . cache. setObject ( image, forKey: url as AnyObject )
101+ Downloader . cache. setImage ( image, forKey: url. absoluteString )
102102 handleSuccess ( image, url)
103103 } else {
104104 failure ? ( ImageDownloadError . urlMismatch)
@@ -117,7 +117,7 @@ public extension UIImageView {
117117 /// and we need to prevent returning the (old) cached entry.
118118 ///
119119 @objc func overrideImageCache( for url: URL , with image: UIImage ) {
120- Downloader . cache. setObject ( image, forKey: url as AnyObject )
120+ Downloader . cache. setImage ( image, forKey: url. absoluteString )
121121
122122 // Remove all cached responses - removing an individual response does not work since iOS 7.
123123 // This feels hacky to do but what else can we do...
@@ -156,14 +156,13 @@ public extension UIImageView {
156156 }
157157 }
158158
159-
160159 /// Private helper structure
161160 ///
162161 private struct Downloader {
163162
164163 /// Stores all of the previously downloaded images.
165164 ///
166- static let cache = NSCache < AnyObject , AnyObject > ( )
165+ static var cache : ImageCaching = ImageCache ( )
167166
168167 /// Key used to associate the current URL.
169168 ///
@@ -173,4 +172,26 @@ public extension UIImageView {
173172 ///
174173 static var taskKey = " downloadTaskKey "
175174 }
175+
176+ /// Changes the default cache used by the image dowloader.
177+ public static func setSharedCache( _ cache: ImageCaching ) {
178+ Downloader . cache = cache
179+ }
180+ }
181+
182+ public protocol ImageCaching {
183+ func setImage( _ image: UIImage , forKey key: String )
184+ func getImage( forKey key: String ) -> UIImage ?
185+ }
186+
187+ private final class ImageCache : ImageCaching {
188+ private let cache = NSCache < NSString , UIImage > ( )
189+
190+ func setImage( _ image: UIImage , forKey key: String ) {
191+ cache. setObject ( image, forKey: key as NSString )
192+ }
193+
194+ func getImage( forKey key: String ) -> UIImage ? {
195+ cache. object ( forKey: key as NSString )
196+ }
176197}
0 commit comments