WKInterfaceImage+Kingfisher.swift 8.4 KB

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