ImageDownloaderDelegate.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. /// Protocol of `ImageDownloader`. This protocol provides a set of methods which are related to image downloader
  28. /// working stages and rules.
  29. public protocol ImageDownloaderDelegate: AnyObject {
  30. /// Called when the `ImageDownloader` object will start downloading an image from a specified URL.
  31. ///
  32. /// - Parameters:
  33. /// - downloader: The `ImageDownloader` object which is used for the downloading operation.
  34. /// - url: URL of the starting request.
  35. /// - request: The request object for the download process.
  36. ///
  37. func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?)
  38. /// Called when the `ImageDownloader` completes a downloading request with success or failure.
  39. ///
  40. /// - Parameters:
  41. /// - downloader: The `ImageDownloader` object which is used for the downloading operation.
  42. /// - url: URL of the original request URL.
  43. /// - response: The response object of the downloading process.
  44. /// - error: The error in case of failure.
  45. ///
  46. func imageDownloader(
  47. _ downloader: ImageDownloader,
  48. didFinishDownloadingImageForURL url: URL,
  49. with response: URLResponse?,
  50. error: Error?)
  51. /// Called when the `ImageDownloader` object successfully downloaded image data from specified URL. This is
  52. /// your last chance to verify or modify the downloaded data before Kingfisher tries to perform addition
  53. /// processing on the image data.
  54. ///
  55. /// - Parameters:
  56. /// - downloader: The `ImageDownloader` object which is used for the downloading operation.
  57. /// - data: The original downloaded data.
  58. /// - dataTask: The data task contains request and response information of the download.
  59. /// - Note:
  60. /// This can be used to pre-process raw image data before creation of `Image` instance (i.e.
  61. /// decrypting or verification). If `nil` returned, the processing is interrupted and a `KingfisherError` with
  62. /// `ResponseErrorReason.dataModifyingFailed` will be raised. You could use this fact to stop the image
  63. /// processing flow if you find the data is corrupted or malformed.
  64. ///
  65. /// If this method is implemented, `imageDownloader(_:didDownload:for:)` will not be called anymore.
  66. func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, with dataTask: SessionDataTask) -> Data?
  67. /// Called when the `ImageDownloader` object successfully downloaded image data from specified URL. This is
  68. /// your last chance to verify or modify the downloaded data before Kingfisher tries to perform addition
  69. /// processing on the image data.
  70. ///
  71. /// - Parameters:
  72. /// - downloader: The `ImageDownloader` object which is used for the downloading operation.
  73. /// - data: The original downloaded data.
  74. /// - url: The URL of the original request URL.
  75. /// - Returns: The data from which Kingfisher should use to create an image. You need to provide valid data
  76. /// which content is one of the supported image file format. Kingfisher will perform process on this
  77. /// data and try to convert it to an image object.
  78. /// - Note:
  79. /// This can be used to pre-process raw image data before creation of `Image` instance (i.e.
  80. /// decrypting or verification). If `nil` returned, the processing is interrupted and a `KingfisherError` with
  81. /// `ResponseErrorReason.dataModifyingFailed` will be raised. You could use this fact to stop the image
  82. /// processing flow if you find the data is corrupted or malformed.
  83. ///
  84. /// If `imageDownloader(_:didDownload:with:)` is implemented, this method will not be called anymore.
  85. func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data?
  86. /// Called when the `ImageDownloader` object successfully downloads and processes an image from specified URL.
  87. ///
  88. /// - Parameters:
  89. /// - downloader: The `ImageDownloader` object which is used for the downloading operation.
  90. /// - image: The downloaded and processed image.
  91. /// - url: URL of the original request URL.
  92. /// - response: The original response object of the downloading process.
  93. ///
  94. func imageDownloader(
  95. _ downloader: ImageDownloader,
  96. didDownload image: KFCrossPlatformImage,
  97. for url: URL,
  98. with response: URLResponse?)
  99. /// Checks if a received HTTP status code is valid or not.
  100. /// By default, a status code in range 200..<400 is considered as valid.
  101. /// If an invalid code is received, the downloader will raise an `KingfisherError` with
  102. /// `ResponseErrorReason.invalidHTTPStatusCode` as its reason.
  103. ///
  104. /// - Parameters:
  105. /// - code: The received HTTP status code.
  106. /// - downloader: The `ImageDownloader` object asks for validate status code.
  107. /// - Returns: Returns a value to indicate whether this HTTP status code is valid or not.
  108. /// - Note: If the default 200 to 400 valid code does not suit your need,
  109. /// you can implement this method to change that behavior.
  110. func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool
  111. /// Called when the task has received a valid HTTP response after it passes other checks such as the status code.
  112. /// You can perform additional checks or verification on the response to determine if the download should be allowed.
  113. ///
  114. /// For example, it is useful if you want to verify some header values in the response before actually starting the
  115. /// download.
  116. ///
  117. /// If implemented, it is your responsibility to call the `completionHandler` with a proper response disposition,
  118. /// such as `.allow` to start the actual downloading or `.cancel` to cancel the task. If `.cancel` is used as the
  119. /// disposition, the downloader will raise an `KingfisherError` with
  120. /// `ResponseErrorReason.cancelledByDelegate` as its reason. If not implemented, any response which passes other
  121. /// checked will be allowed and the download starts.
  122. ///
  123. /// - Parameters:
  124. /// - downloader: The `ImageDownloader` object which is used for the downloading operation.
  125. /// - response: The original response object of the downloading process.
  126. /// - completionHandler: A completion handler that receives the disposition for the download task. You must call
  127. /// this handler with either `.allow` or `.cancel`.
  128. func imageDownloader(
  129. _ downloader: ImageDownloader,
  130. didReceive response: URLResponse,
  131. completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
  132. }
  133. // Default implementation for `ImageDownloaderDelegate`.
  134. extension ImageDownloaderDelegate {
  135. public func imageDownloader(
  136. _ downloader: ImageDownloader,
  137. willDownloadImageForURL url: URL,
  138. with request: URLRequest?) {}
  139. public func imageDownloader(
  140. _ downloader: ImageDownloader,
  141. didFinishDownloadingImageForURL url: URL,
  142. with response: URLResponse?,
  143. error: Error?) {}
  144. public func imageDownloader(
  145. _ downloader: ImageDownloader,
  146. didDownload image: KFCrossPlatformImage,
  147. for url: URL,
  148. with response: URLResponse?) {}
  149. public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool {
  150. return (200..<400).contains(code)
  151. }
  152. public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, with task: SessionDataTask) -> Data? {
  153. guard let url = task.originalURL else {
  154. return data
  155. }
  156. return imageDownloader(downloader, didDownload: data, for: url)
  157. }
  158. public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data? {
  159. return data
  160. }
  161. public func imageDownloader(
  162. _ downloader: ImageDownloader,
  163. didReceive response: URLResponse,
  164. completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  165. completionHandler(.allow)
  166. }
  167. }