TVMonogramView+Kingfisher.swift 8.6 KB

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