CPListItem+Kingfisher.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. //
  2. // CPListItem+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Wayne Hartman on 2021-08-29.
  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. #if canImport(CarPlay) && !targetEnvironment(macCatalyst)
  27. import CarPlay
  28. @available(iOS 14.0, *)
  29. extension KingfisherWrapper where Base: CPListItem {
  30. // MARK: Setting Image
  31. /// Sets an image to the image view with a source.
  32. ///
  33. /// - Parameters:
  34. /// - source: The `Source` object contains information about the image.
  35. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  36. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  37. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  38. /// `expectedContentLength`, this block will not be called.
  39. /// - completionHandler: Called when the image retrieved and set finished.
  40. /// - Returns: A task represents the image downloading.
  41. ///
  42. /// - Note:
  43. ///
  44. /// Internally, this method will use `KingfisherManager` to get the requested source
  45. /// Since this method will perform UI changes, you must call it from the main thread.
  46. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  47. ///
  48. @discardableResult
  49. public func setImage(
  50. with source: Source?,
  51. placeholder: KFCrossPlatformImage? = nil,
  52. options: KingfisherOptionsInfo? = nil,
  53. progressBlock: DownloadProgressBlock? = nil,
  54. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  55. {
  56. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? []))
  57. return setImage(
  58. with: source,
  59. placeholder: placeholder,
  60. parsedOptions: options,
  61. progressBlock: progressBlock,
  62. completionHandler: completionHandler
  63. )
  64. }
  65. /// Sets an image to the image view with a requested resource.
  66. ///
  67. /// - Parameters:
  68. /// - resource: The `Resource` object contains information about the image.
  69. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  70. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  71. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  72. /// `expectedContentLength`, this block will not be called.
  73. /// - completionHandler: Called when the image retrieved and set finished.
  74. /// - Returns: A task represents the image downloading.
  75. ///
  76. /// - Note:
  77. ///
  78. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  79. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  80. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  81. ///
  82. @discardableResult
  83. public func setImage(
  84. with resource: Resource?,
  85. placeholder: KFCrossPlatformImage? = nil,
  86. options: KingfisherOptionsInfo? = nil,
  87. progressBlock: DownloadProgressBlock? = nil,
  88. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  89. {
  90. return setImage(
  91. with: resource?.convertToSource(),
  92. placeholder: placeholder,
  93. options: options,
  94. progressBlock: progressBlock,
  95. completionHandler: completionHandler)
  96. }
  97. func setImage(
  98. with source: Source?,
  99. placeholder: KFCrossPlatformImage? = nil,
  100. parsedOptions: KingfisherParsedOptionsInfo,
  101. progressBlock: DownloadProgressBlock? = nil,
  102. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  103. {
  104. var mutatingSelf = self
  105. guard let source = source else {
  106. /**
  107. * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
  108. * to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
  109. * which allows >=14.5 SDK to set a `nil` image. This compile check allows
  110. * newer SDK users to set the image to `nil`, while still allowing older SDK
  111. * users to compile the framework.
  112. */
  113. #if compiler(>=5.4)
  114. self.base.setImage(placeholder)
  115. #else
  116. if let placeholder = placeholder {
  117. self.base.setImage(placeholder)
  118. }
  119. #endif
  120. mutatingSelf.taskIdentifier = nil
  121. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  122. return nil
  123. }
  124. var options = parsedOptions
  125. if !options.keepCurrentImageWhileLoading {
  126. /**
  127. * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
  128. * to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
  129. * which allows >=14.5 SDK to set a `nil` image. This compile check allows
  130. * newer SDK users to set the image to `nil`, while still allowing older SDK
  131. * users to compile the framework.
  132. */
  133. #if compiler(>=5.4)
  134. self.base.setImage(placeholder)
  135. #else // Let older SDK users deal with the older behavior.
  136. if let placeholder = placeholder {
  137. self.base.setImage(placeholder)
  138. }
  139. #endif
  140. }
  141. let issuedIdentifier = Source.Identifier.next()
  142. mutatingSelf.taskIdentifier = issuedIdentifier
  143. if let block = progressBlock {
  144. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  145. }
  146. let task = KingfisherManager.shared.retrieveImage(
  147. with: source,
  148. options: options,
  149. downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
  150. progressiveImageSetter: { self.base.setImage($0) },
  151. referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
  152. completionHandler: { result in
  153. CallbackQueue.mainCurrentOrAsync.execute {
  154. guard issuedIdentifier == self.taskIdentifier else {
  155. let reason: KingfisherError.ImageSettingErrorReason
  156. do {
  157. let value = try result.get()
  158. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  159. } catch {
  160. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  161. }
  162. let error = KingfisherError.imageSettingError(reason: reason)
  163. completionHandler?(.failure(error))
  164. return
  165. }
  166. mutatingSelf.imageTask = nil
  167. mutatingSelf.taskIdentifier = nil
  168. switch result {
  169. case .success(let value):
  170. self.base.setImage(value.image)
  171. completionHandler?(result)
  172. case .failure:
  173. if let image = options.onFailureImage {
  174. /**
  175. * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
  176. * to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
  177. * which allows >=14.5 SDK to set a `nil` image. This compile check allows
  178. * newer SDK users to set the image to `nil`, while still allowing older SDK
  179. * users to compile the framework.
  180. */
  181. #if compiler(>=5.4)
  182. self.base.setImage(image)
  183. #else // Let older SDK users deal with the older behavior.
  184. if let unwrapped = image {
  185. self.base.setImage(unwrapped)
  186. }
  187. #endif
  188. }
  189. completionHandler?(result)
  190. }
  191. }
  192. }
  193. )
  194. mutatingSelf.imageTask = task
  195. return task
  196. }
  197. // MARK: Cancelling Image
  198. /// Cancel the image download task bounded to the image view if it is running.
  199. /// Nothing will happen if the downloading has already finished.
  200. public func cancelDownloadTask() {
  201. imageTask?.cancel()
  202. }
  203. }
  204. private var taskIdentifierKey: Void?
  205. private var imageTaskKey: Void?
  206. // MARK: Properties
  207. extension KingfisherWrapper where Base: CPListItem {
  208. public private(set) var taskIdentifier: Source.Identifier.Value? {
  209. get {
  210. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  211. return box?.value
  212. }
  213. set {
  214. let box = newValue.map { Box($0) }
  215. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  216. }
  217. }
  218. private var imageTask: DownloadTask? {
  219. get { return getAssociatedObject(base, &imageTaskKey) }
  220. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  221. }
  222. }
  223. #endif