ImageDownloaderDelegate.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. //
  2. // ImageDownloaderDelegate.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2018/10/11.
  6. //
  7. // Copyright (c) 2019 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. import Foundation
  27. #if os(macOS)
  28. import AppKit
  29. #else
  30. import UIKit
  31. #endif
  32. /// Protocol for handling events for ``ImageDownloader``.
  33. ///
  34. /// This delegate protocol provides a set of methods related to the stages and rules of the image downloader. You use
  35. /// the provided methods to inspect the downloader working phases or respond to some events to make decisions.
  36. public protocol ImageDownloaderDelegate: AnyObject {
  37. /// Called when the ``ImageDownloader`` object is about to start downloading an image from a specified URL.
  38. ///
  39. /// - Parameters:
  40. /// - downloader: The ``ImageDownloader`` object used for the downloading operation.
  41. /// - url: The URL of the starting request.
  42. /// - request: The request object for the download process.
  43. func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?)
  44. /// Called when the ``ImageDownloader`` completes a downloading request with success or failure.
  45. ///
  46. /// - Parameters:
  47. /// - downloader: The ``ImageDownloader`` object used for the downloading operation.
  48. /// - url: The URL of the original request.
  49. /// - response: The response object of the downloading process.
  50. /// - error: The error in case of failure.
  51. func imageDownloader(
  52. _ downloader: ImageDownloader,
  53. didFinishDownloadingImageForURL url: URL,
  54. with response: URLResponse?,
  55. error: (any Error)?)
  56. /// Called when the ``ImageDownloader`` object successfully downloads image data with a specified task.
  57. ///
  58. /// This is your last chance to verify or modify the downloaded data before Kingfisher attempts to perform
  59. /// additional processing on the image data.
  60. ///
  61. /// - Parameters:
  62. /// - downloader: The ``ImageDownloader`` object used for the downloading operation.
  63. /// - data: The original downloaded data.
  64. /// - task: The data task containing request and response information for the download.
  65. /// - Returns: The data that Kingfisher should use to create an image. You need to provide valid data that is in
  66. /// one of the supported image file formats. Kingfisher will process this data and attempt to convert it into an
  67. /// image object.
  68. func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, with task: SessionDataTask) -> Data?
  69. /// Called when the ``ImageDownloader`` object successfully downloads image data from a specified URL.
  70. ///
  71. /// This is your last chance to verify or modify the downloaded data before Kingfisher attempts to perform
  72. /// additional processing on the image data.
  73. ///
  74. /// - Parameters:
  75. /// - downloader: The ``ImageDownloader`` object used for the downloading operation.
  76. /// - data: The original downloaded data.
  77. /// - url: The URL of the original request.
  78. ///
  79. /// - Returns: The data that Kingfisher should use to create an image. You need to provide valid data that is in
  80. /// one of the supported image file formats. Kingfisher will process this data and attempt to convert it into an
  81. /// image object.
  82. ///
  83. /// This method can be used to preprocess raw image data before the creation of the `Image` instance (e.g.,
  84. /// decrypting or verification). If `nil` is returned, the processing is interrupted and a
  85. /// ``KingfisherError/ResponseErrorReason/dataModifyingFailed(task:)`` error will be raised. You can use this fact
  86. /// to stop the image processing flow if you find that the data is corrupted or malformed.
  87. ///
  88. /// > If the ``SessionDataTask`` version of `imageDownloader(_:didDownload:with:)` is implemented, this method will
  89. /// > not be called anymore.
  90. func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data?
  91. /// Called when the ``ImageDownloader`` object successfully downloads and processes an image from a specified URL.
  92. ///
  93. /// - Parameters:
  94. /// - downloader: The ``ImageDownloader`` object used for the downloading operation.
  95. /// - image: The downloaded and processed image.
  96. /// - url: The URL of the original request.
  97. /// - response: The original response object of the downloading process.
  98. func imageDownloader(
  99. _ downloader: ImageDownloader,
  100. didDownload image: KFCrossPlatformImage,
  101. for url: URL,
  102. with response: URLResponse?)
  103. /// Checks if a received HTTP status code is valid or not.
  104. ///
  105. /// By default, a status code in the range `200..<400` is considered as valid. If an invalid code is received,
  106. /// the downloader will raise a ``KingfisherError/ResponseErrorReason/invalidHTTPStatusCode(response:)`` error.
  107. ///
  108. /// - Parameters:
  109. /// - code: The received HTTP status code.
  110. /// - downloader: The ``ImageDownloader`` object requesting validation of the status code.
  111. /// - Returns: A value indicating whether this HTTP status code is valid or not.
  112. ///
  113. /// > If the default range of `200..<400` as valid codes does not suit your needs, you can implement this method to
  114. /// change that behavior.
  115. func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool
  116. /// Called when the task has received a valid HTTP response after passing other checks such as the status code.
  117. /// You can perform additional checks or verifications on the response to determine if the download should be
  118. /// allowed or cancelled.
  119. ///
  120. /// For example, this is useful if you want to verify some header values in the response before actually starting
  121. /// the download.
  122. ///
  123. /// If implemented, you have to return a proper response disposition, such as `.allow` to start the actual
  124. /// downloading or `.cancel` to cancel the task. If `.cancel` is used as the disposition, the downloader will raise
  125. /// a ``KingfisherError/ResponseErrorReason/cancelledByDelegate(response:)`` error. If not implemented, any response
  126. /// that passes other checks will be allowed, and the download will start.
  127. ///
  128. /// - Parameters:
  129. /// - downloader: The `ImageDownloader` object used for the downloading operation.
  130. /// - response: The original response object of the downloading process.
  131. ///
  132. /// - Returns: The disposition for the download task. You have to return either `.allow` or `.cancel`.
  133. func imageDownloader(
  134. _ downloader: ImageDownloader,
  135. didReceive response: URLResponse
  136. ) async -> URLSession.ResponseDisposition
  137. }
  138. // Default implementation for `ImageDownloaderDelegate`.
  139. extension ImageDownloaderDelegate {
  140. public func imageDownloader(
  141. _ downloader: ImageDownloader,
  142. willDownloadImageForURL url: URL,
  143. with request: URLRequest?) {}
  144. public func imageDownloader(
  145. _ downloader: ImageDownloader,
  146. didFinishDownloadingImageForURL url: URL,
  147. with response: URLResponse?,
  148. error: (any Error)?) {}
  149. public func imageDownloader(
  150. _ downloader: ImageDownloader,
  151. didDownload image: KFCrossPlatformImage,
  152. for url: URL,
  153. with response: URLResponse?) {}
  154. public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool {
  155. return (200..<400).contains(code)
  156. }
  157. public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, with task: SessionDataTask) -> Data? {
  158. guard let url = task.originalURL else {
  159. return data
  160. }
  161. return imageDownloader(downloader, didDownload: data, for: url)
  162. }
  163. public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data? {
  164. return data
  165. }
  166. public func imageDownloader(
  167. _ downloader: ImageDownloader,
  168. didReceive response: URLResponse
  169. ) async -> URLSession.ResponseDisposition {
  170. .allow
  171. }
  172. }