WKInterfaceImage+Kingfisher.swift 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. //
  2. // WKInterfaceImage+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Rodrigo Borges Soares on 04/05/18.
  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(WatchKit)
  27. import WatchKit
  28. @MainActor
  29. extension KingfisherWrapper where Base: WKInterfaceImage {
  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: (@Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  55. {
  56. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  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: (@Sendable (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: (@Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  103. {
  104. var mutatingSelf = self
  105. guard let source = source else {
  106. base.setImage(placeholder)
  107. mutatingSelf.taskIdentifier = nil
  108. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  109. return nil
  110. }
  111. var options = parsedOptions
  112. if !options.keepCurrentImageWhileLoading {
  113. base.setImage(placeholder)
  114. }
  115. let issuedIdentifier = Source.Identifier.next()
  116. mutatingSelf.taskIdentifier = issuedIdentifier
  117. if let block = progressBlock {
  118. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  119. }
  120. let task = KingfisherManager.shared.retrieveImage(
  121. with: source,
  122. options: options,
  123. downloadTaskUpdated: { task in
  124. Task { @MainActor in mutatingSelf.imageTask = task }
  125. },
  126. progressiveImageSetter: { self.base.setImage($0) },
  127. referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
  128. completionHandler: { result in
  129. CallbackQueueMain.currentOrAsync {
  130. guard issuedIdentifier == self.taskIdentifier else {
  131. let reason: KingfisherError.ImageSettingErrorReason
  132. do {
  133. let value = try result.get()
  134. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  135. } catch {
  136. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  137. }
  138. let error = KingfisherError.imageSettingError(reason: reason)
  139. completionHandler?(.failure(error))
  140. return
  141. }
  142. mutatingSelf.imageTask = nil
  143. mutatingSelf.taskIdentifier = nil
  144. switch result {
  145. case .success(let value):
  146. self.base.setImage(value.image)
  147. completionHandler?(result)
  148. case .failure:
  149. if let image = options.onFailureImage {
  150. self.base.setImage(image)
  151. }
  152. completionHandler?(result)
  153. }
  154. }
  155. }
  156. )
  157. mutatingSelf.imageTask = task
  158. return task
  159. }
  160. // MARK: Cancelling Image
  161. /// Cancel the image download task bounded to the image view if it is running.
  162. /// Nothing will happen if the downloading has already finished.
  163. public func cancelDownloadTask() {
  164. imageTask?.cancel()
  165. }
  166. }
  167. @MainActor private var taskIdentifierKey: Void?
  168. @MainActor private var imageTaskKey: Void?
  169. // MARK: Properties
  170. @MainActor
  171. extension KingfisherWrapper where Base: WKInterfaceImage {
  172. public private(set) var taskIdentifier: Source.Identifier.Value? {
  173. get {
  174. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  175. return box?.value
  176. }
  177. set {
  178. let box = newValue.map { Box($0) }
  179. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  180. }
  181. }
  182. private var imageTask: DownloadTask? {
  183. get { return getAssociatedObject(base, &imageTaskKey) }
  184. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  185. }
  186. }
  187. #endif