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