WKInterfaceImage+Kingfisher.swift 7.9 KB

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