WKInterfaceImage+Kingfisher.swift 8.3 KB

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