TVMonogramView+Kingfisher.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. let task = KingfisherManager.shared.retrieveImage(
  90. with: source,
  91. options: options,
  92. downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
  93. progressiveImageSetter: { self.base.image = $0 },
  94. referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
  95. completionHandler: { result in
  96. CallbackQueue.mainCurrentOrAsync.execute {
  97. guard issuedIdentifier == self.taskIdentifier else {
  98. let reason: KingfisherError.ImageSettingErrorReason
  99. do {
  100. let value = try result.get()
  101. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  102. } catch {
  103. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  104. }
  105. let error = KingfisherError.imageSettingError(reason: reason)
  106. completionHandler?(.failure(error))
  107. return
  108. }
  109. mutatingSelf.imageTask = nil
  110. mutatingSelf.taskIdentifier = nil
  111. switch result {
  112. case .success(let value):
  113. self.base.image = value.image
  114. completionHandler?(result)
  115. case .failure:
  116. if let image = options.onFailureImage {
  117. self.base.image = image
  118. }
  119. completionHandler?(result)
  120. }
  121. }
  122. }
  123. )
  124. mutatingSelf.imageTask = task
  125. return task
  126. }
  127. /// Sets an image to the image view with a requested resource.
  128. ///
  129. /// - Parameters:
  130. /// - resource: The `Resource` object contains information about the image.
  131. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  132. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  133. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  134. /// `expectedContentLength`, this block will not be called.
  135. /// - completionHandler: Called when the image retrieved and set finished.
  136. /// - Returns: A task represents the image downloading.
  137. ///
  138. /// - Note:
  139. ///
  140. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  141. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  142. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  143. ///
  144. @discardableResult
  145. public func setImage(
  146. with resource: Resource?,
  147. placeholder: KFCrossPlatformImage? = nil,
  148. options: KingfisherOptionsInfo? = nil,
  149. progressBlock: DownloadProgressBlock? = nil,
  150. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  151. {
  152. return setImage(
  153. with: resource?.convertToSource(),
  154. placeholder: placeholder,
  155. options: options,
  156. progressBlock: progressBlock,
  157. completionHandler: completionHandler)
  158. }
  159. // MARK: Cancelling Image
  160. /// Cancel the image download task bounded to the image view if it is running.
  161. /// Nothing will happen if the downloading has already finished.
  162. public func cancelDownloadTask() {
  163. imageTask?.cancel()
  164. }
  165. }
  166. private var taskIdentifierKey: Void?
  167. private var imageTaskKey: Void?
  168. // MARK: Properties
  169. @available(tvOS 12.0, *)
  170. extension KingfisherWrapper where Base: TVMonogramView {
  171. public private(set) var taskIdentifier: Source.Identifier.Value? {
  172. get {
  173. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  174. return box?.value
  175. }
  176. set {
  177. let box = newValue.map { Box($0) }
  178. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  179. }
  180. }
  181. private var imageTask: DownloadTask? {
  182. get { return getAssociatedObject(base, &imageTaskKey) }
  183. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  184. }
  185. }
  186. #endif