ImageDownloader.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. //
  2. // ImageDownloader.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  6. //
  7. // Copyright (c) 2017 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if os(macOS)
  27. import AppKit
  28. #else
  29. import UIKit
  30. #endif
  31. /// Progress update block of downloader.
  32. public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
  33. /// Completion block of downloader.
  34. public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> ())
  35. /// Download task.
  36. public struct RetrieveImageDownloadTask {
  37. let internalTask: URLSessionDataTask
  38. /// Downloader by which this task is intialized.
  39. public private(set) weak var ownerDownloader: ImageDownloader?
  40. /**
  41. Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error.
  42. */
  43. public func cancel() {
  44. ownerDownloader?.cancelDownloadingTask(self)
  45. }
  46. /// The original request URL of this download task.
  47. public var url: URL? {
  48. return internalTask.originalRequest?.url
  49. }
  50. /// The relative priority of this download task.
  51. /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task.
  52. /// The value for it is between 0.0~1.0. Default priority is value of 0.5.
  53. /// See documentation on `priority` of `NSURLSessionTask` for more about it.
  54. public var priority: Float {
  55. get {
  56. return internalTask.priority
  57. }
  58. set {
  59. internalTask.priority = newValue
  60. }
  61. }
  62. }
  63. ///The code of errors which `ImageDownloader` might encountered.
  64. public enum KingfisherError: Int {
  65. /// badData: The downloaded data is not an image or the data is corrupted.
  66. case badData = 10000
  67. /// notModified: The remote server responsed a 304 code. No image data downloaded.
  68. case notModified = 10001
  69. /// The HTTP status code in response is not valid. If an invalid
  70. /// code error received, you could check the value under `KingfisherErrorStatusCodeKey`
  71. /// in `userInfo` to see the code.
  72. case invalidStatusCode = 10002
  73. /// notCached: The image rquested is not in cache but .onlyFromCache is activated.
  74. case notCached = 10003
  75. /// The URL is invalid.
  76. case invalidURL = 20000
  77. /// The downloading task is cancelled before started.
  78. case downloadCancelledBeforeStarting = 30000
  79. }
  80. /// Key will be used in the `userInfo` of `.invalidStatusCode`
  81. public let KingfisherErrorStatusCodeKey = "statusCode"
  82. /// Protocol of `ImageDownloader`.
  83. public protocol ImageDownloaderDelegate: class {
  84. /**
  85. Called when the `ImageDownloader` object successfully downloaded an image from specified URL.
  86. - parameter downloader: The `ImageDownloader` object finishes the downloading.
  87. - parameter image: Downloaded image.
  88. - parameter url: URL of the original request URL.
  89. - parameter response: The response object of the downloading process.
  90. */
  91. func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?)
  92. /**
  93. Called when the `ImageDownloader` object starts to download an image from specified URL.
  94. - parameter downloader: The `ImageDownloader` object starts the downloading.
  95. - parameter url: URL of the original request.
  96. - parameter response: The request object of the downloading process.
  97. */
  98. func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?)
  99. /**
  100. Check if a received HTTP status code is valid or not.
  101. By default, a status code between 200 to 400 (excluded) is considered as valid.
  102. If an invalid code is received, the downloader will raise an .invalidStatusCode error.
  103. It has a `userInfo` which includes this statusCode and localizedString error message.
  104. - parameter code: The received HTTP status code.
  105. - parameter downloader: The `ImageDownloader` object asking for validate status code.
  106. - returns: Whether this HTTP status code is valid or not.
  107. - Note: If the default 200 to 400 valid code does not suit your need,
  108. you can implement this method to change that behavior.
  109. */
  110. func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool
  111. }
  112. extension ImageDownloaderDelegate {
  113. public func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {}
  114. public func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) {}
  115. public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool {
  116. return (200..<400).contains(code)
  117. }
  118. }
  119. /// Protocol indicates that an authentication challenge could be handled.
  120. public protocol AuthenticationChallengeResponsable: class {
  121. /**
  122. Called when an session level authentication challenge is received.
  123. This method provide a chance to handle and response to the authentication challenge before downloading could start.
  124. - parameter downloader: The downloader which receives this challenge.
  125. - parameter challenge: An object that contains the request for authentication.
  126. - parameter completionHandler: A handler that your delegate method must call.
  127. - Note: This method is a forward from `URLSessionDelegate.urlSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `URLSessionDelegate`.
  128. */
  129. func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  130. /**
  131. Called when an session level authentication challenge is received.
  132. This method provide a chance to handle and response to the authentication challenge before downloading could start.
  133. - parameter downloader: The downloader which receives this challenge.
  134. - parameter task: The task whose request requires authentication.
  135. - parameter challenge: An object that contains the request for authentication.
  136. - parameter completionHandler: A handler that your delegate method must call.
  137. - Note: This method is a forward from `URLSessionTaskDelegate.urlSession(:task:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `URLSessionTaskDelegate`.
  138. */
  139. func downloader(_ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  140. }
  141. extension AuthenticationChallengeResponsable {
  142. func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  143. if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  144. if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) {
  145. let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
  146. completionHandler(.useCredential, credential)
  147. return
  148. }
  149. }
  150. completionHandler(.performDefaultHandling, nil)
  151. }
  152. func downloader(_ downloader: ImageDownloader, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  153. completionHandler(.performDefaultHandling, nil)
  154. }
  155. }
  156. /// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server.
  157. open class ImageDownloader {
  158. class ImageFetchLoad {
  159. var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]()
  160. var responseData = NSMutableData()
  161. var downloadTaskCount = 0
  162. var downloadTask: RetrieveImageDownloadTask?
  163. var cancelSemaphore: DispatchSemaphore?
  164. }
  165. // MARK: - Public property
  166. /// The duration before the download is timeout. Default is 15 seconds.
  167. open var downloadTimeout: TimeInterval = 15.0
  168. /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored.
  169. /// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`.
  170. /// If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead.
  171. open var trustedHosts: Set<String>?
  172. /// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used.
  173. /// You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly.
  174. open var sessionConfiguration = URLSessionConfiguration.ephemeral {
  175. didSet {
  176. session?.invalidateAndCancel()
  177. session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: OperationQueue.main)
  178. }
  179. }
  180. /// Whether the download requests should use pipeling or not. Default is false.
  181. open var requestsUsePipelining = false
  182. fileprivate let sessionHandler: ImageDownloaderSessionHandler
  183. fileprivate var session: URLSession?
  184. /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
  185. open weak var delegate: ImageDownloaderDelegate?
  186. /// A responder for authentication challenge.
  187. /// Downloader will forward the received authentication challenge for the downloading session to this responder.
  188. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable?
  189. // MARK: - Internal property
  190. let barrierQueue: DispatchQueue
  191. let processQueue: DispatchQueue
  192. let cancelQueue: DispatchQueue
  193. typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?)
  194. var fetchLoads = [URL: ImageFetchLoad]()
  195. // MARK: - Public method
  196. /// The default downloader.
  197. public static let `default` = ImageDownloader(name: "default")
  198. /**
  199. Init a downloader with name.
  200. - parameter name: The name for the downloader. It should not be empty.
  201. - returns: The downloader object.
  202. */
  203. public init(name: String) {
  204. if name.isEmpty {
  205. fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.")
  206. }
  207. barrierQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Barrier.\(name)", attributes: .concurrent)
  208. processQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process.\(name)", attributes: .concurrent)
  209. cancelQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Cancel.\(name)")
  210. sessionHandler = ImageDownloaderSessionHandler()
  211. // Provide a default implement for challenge responder.
  212. authenticationChallengeResponder = sessionHandler
  213. session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main)
  214. }
  215. deinit {
  216. session?.invalidateAndCancel()
  217. }
  218. func fetchLoad(for url: URL) -> ImageFetchLoad? {
  219. var fetchLoad: ImageFetchLoad?
  220. barrierQueue.sync(flags: .barrier) { fetchLoad = fetchLoads[url] }
  221. return fetchLoad
  222. }
  223. /**
  224. Download an image with a URL and option.
  225. - parameter url: Target URL.
  226. - parameter retrieveImageTask: The task to cooporate with cache. Pass `nil` if you are not trying to use downloader and cache.
  227. - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`.
  228. - parameter progressBlock: Called when the download progress updated.
  229. - parameter completionHandler: Called when the download progress finishes.
  230. - returns: A downloading task. You could call `cancel` on it to stop the downloading process.
  231. */
  232. @discardableResult
  233. open func downloadImage(with url: URL,
  234. retrieveImageTask: RetrieveImageTask? = nil,
  235. options: KingfisherOptionsInfo? = nil,
  236. progressBlock: ImageDownloaderProgressBlock? = nil,
  237. completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask?
  238. {
  239. if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting {
  240. completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil)
  241. return nil
  242. }
  243. let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout
  244. // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL.
  245. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)
  246. request.httpShouldUsePipelining = requestsUsePipelining
  247. if let modifier = options?.modifier {
  248. guard let r = modifier.modified(for: request) else {
  249. completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil)
  250. return nil
  251. }
  252. request = r
  253. }
  254. // There is a possiblility that request modifier changed the url to `nil` or empty.
  255. guard let url = request.url, !url.absoluteString.isEmpty else {
  256. completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), nil, nil)
  257. return nil
  258. }
  259. var downloadTask: RetrieveImageDownloadTask?
  260. setup(progressBlock: progressBlock, with: completionHandler, for: url, options: options) {(session, fetchLoad) -> Void in
  261. if fetchLoad.downloadTask == nil {
  262. let dataTask = session.dataTask(with: request)
  263. fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self)
  264. dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority
  265. dataTask.resume()
  266. self.delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request)
  267. // Hold self while the task is executing.
  268. self.sessionHandler.downloadHolder = self
  269. }
  270. fetchLoad.downloadTaskCount += 1
  271. downloadTask = fetchLoad.downloadTask
  272. retrieveImageTask?.downloadTask = downloadTask
  273. }
  274. return downloadTask
  275. }
  276. }
  277. // MARK: - Download method
  278. extension ImageDownloader {
  279. // A single key may have multiple callbacks. Only download once.
  280. func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, options: KingfisherOptionsInfo?, started: @escaping ((URLSession, ImageFetchLoad) -> Void)) {
  281. func prepareFetchLoad() {
  282. barrierQueue.sync(flags: .barrier) {
  283. let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad()
  284. let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler)
  285. loadObjectForURL.contents.append((callbackPair, options ?? KingfisherEmptyOptionsInfo))
  286. fetchLoads[url] = loadObjectForURL
  287. if let session = session {
  288. started(session, loadObjectForURL)
  289. }
  290. }
  291. }
  292. if let fetchLoad = fetchLoad(for: url), fetchLoad.downloadTaskCount == 0 {
  293. if fetchLoad.cancelSemaphore == nil {
  294. fetchLoad.cancelSemaphore = DispatchSemaphore(value: 0)
  295. }
  296. cancelQueue.async {
  297. _ = fetchLoad.cancelSemaphore?.wait(timeout: .distantFuture)
  298. fetchLoad.cancelSemaphore = nil
  299. prepareFetchLoad()
  300. }
  301. } else {
  302. prepareFetchLoad()
  303. }
  304. }
  305. func cancelDownloadingTask(_ task: RetrieveImageDownloadTask) {
  306. barrierQueue.sync(flags: .barrier) {
  307. if let URL = task.internalTask.originalRequest?.url, let imageFetchLoad = self.fetchLoads[URL] {
  308. imageFetchLoad.downloadTaskCount -= 1
  309. if imageFetchLoad.downloadTaskCount == 0 {
  310. task.internalTask.cancel()
  311. }
  312. }
  313. }
  314. }
  315. func clean(for url: URL) {
  316. barrierQueue.sync(flags: .barrier) {
  317. fetchLoads.removeValue(forKey: url)
  318. return
  319. }
  320. }
  321. }
  322. // MARK: - NSURLSessionDataDelegate
  323. /// Delegate class for `NSURLSessionTaskDelegate`.
  324. /// The session object will hold its delegate until it gets invalidated.
  325. /// If we use `ImageDownloader` as the session delegate, it will not be released.
  326. /// So we need an additional handler to break the retain cycle.
  327. // See https://github.com/onevcat/Kingfisher/issues/235
  328. class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponsable {
  329. // The holder will keep downloader not released while a data task is being executed.
  330. // It will be set when the task started, and reset when the task finished.
  331. var downloadHolder: ImageDownloader?
  332. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  333. guard let downloader = downloadHolder else {
  334. completionHandler(.cancel)
  335. return
  336. }
  337. if let statusCode = (response as? HTTPURLResponse)?.statusCode,
  338. let url = dataTask.originalRequest?.url,
  339. !(downloader.delegate ?? downloader).isValidStatusCode(statusCode, for: downloader)
  340. {
  341. let error = NSError(domain: KingfisherErrorDomain,
  342. code: KingfisherError.invalidStatusCode.rawValue,
  343. userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)])
  344. callCompletionHandlerFailure(error: error, url: url)
  345. }
  346. completionHandler(.allow)
  347. }
  348. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  349. guard let downloader = downloadHolder else {
  350. return
  351. }
  352. if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) {
  353. fetchLoad.responseData.append(data)
  354. if let expectedLength = dataTask.response?.expectedContentLength {
  355. for content in fetchLoad.contents {
  356. DispatchQueue.main.async {
  357. content.callback.progressBlock?(Int64(fetchLoad.responseData.length), expectedLength)
  358. }
  359. }
  360. }
  361. }
  362. }
  363. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  364. guard let url = task.originalRequest?.url else {
  365. return
  366. }
  367. guard error == nil else {
  368. callCompletionHandlerFailure(error: error!, url: url)
  369. return
  370. }
  371. processImage(for: task, url: url)
  372. }
  373. /**
  374. This method is exposed since the compiler requests. Do not call it.
  375. */
  376. func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  377. guard let downloader = downloadHolder else {
  378. return
  379. }
  380. downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler)
  381. }
  382. func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  383. guard let downloader = downloadHolder else {
  384. return
  385. }
  386. downloader.authenticationChallengeResponder?.downloader(downloader, task: task, didReceive: challenge, completionHandler: completionHandler)
  387. }
  388. private func cleanFetchLoad(for url: URL) {
  389. guard let downloader = downloadHolder else {
  390. return
  391. }
  392. downloader.clean(for: url)
  393. if downloader.fetchLoads.isEmpty {
  394. downloadHolder = nil
  395. }
  396. }
  397. private func callCompletionHandlerFailure(error: Error, url: URL) {
  398. guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else {
  399. return
  400. }
  401. // We need to clean the fetch load first, before actually calling completion handler.
  402. cleanFetchLoad(for: url)
  403. var leftSignal: Int
  404. repeat {
  405. leftSignal = fetchLoad.cancelSemaphore?.signal() ?? 0
  406. } while leftSignal != 0
  407. for content in fetchLoad.contents {
  408. content.options.callbackDispatchQueue.safeAsync {
  409. content.callback.completionHandler?(nil, error as NSError, url, nil)
  410. }
  411. }
  412. }
  413. private func processImage(for task: URLSessionTask, url: URL) {
  414. guard let downloader = downloadHolder else {
  415. return
  416. }
  417. // We are on main queue when receiving this.
  418. downloader.processQueue.async {
  419. guard let fetchLoad = downloader.fetchLoad(for: url) else {
  420. return
  421. }
  422. self.cleanFetchLoad(for: url)
  423. let data = fetchLoad.responseData as Data
  424. // Cache the processed images. So we do not need to re-process the image if using the same processor.
  425. // Key is the identifier of processor.
  426. var imageCache: [String: Image] = [:]
  427. for content in fetchLoad.contents {
  428. let options = content.options
  429. let completionHandler = content.callback.completionHandler
  430. let callbackQueue = options.callbackDispatchQueue
  431. let processor = options.processor
  432. var image = imageCache[processor.identifier]
  433. if image == nil {
  434. image = processor.process(item: .data(data), options: options)
  435. // Add the processed image to cache.
  436. // If `image` is nil, nothing will happen (since the key is not existing before).
  437. imageCache[processor.identifier] = image
  438. }
  439. if let image = image {
  440. downloader.delegate?.imageDownloader(downloader, didDownload: image, for: url, with: task.response)
  441. if options.backgroundDecode {
  442. let decodedImage = image.kf.decoded
  443. callbackQueue.safeAsync { completionHandler?(decodedImage, nil, url, data) }
  444. } else {
  445. callbackQueue.safeAsync { completionHandler?(image, nil, url, data) }
  446. }
  447. } else {
  448. if let res = task.response as? HTTPURLResponse , res.statusCode == 304 {
  449. let notModified = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil)
  450. completionHandler?(nil, notModified, url, nil)
  451. continue
  452. }
  453. let badData = NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil)
  454. callbackQueue.safeAsync { completionHandler?(nil, badData, url, nil) }
  455. }
  456. }
  457. }
  458. }
  459. }
  460. // Placeholder. For retrieving extension methods of ImageDownloaderDelegate
  461. extension ImageDownloader: ImageDownloaderDelegate {}