TVMonogramView+Kingfisher.swift 8.6 KB

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