You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

205 lines
8.4 KiB

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