ImageView+Kingfisher.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. //
  2. // ImageView+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  6. //
  7. // Copyright (c) 2017 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 os(macOS)
  27. import AppKit
  28. #else
  29. import UIKit
  30. #endif
  31. // MARK: - Extension methods.
  32. /**
  33. * Set image to use from web.
  34. */
  35. extension Kingfisher where Base: ImageView {
  36. /**
  37. Set an image with a resource, a placeholder image, options, progress handler and completion handler.
  38. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
  39. - parameter placeholder: A placeholder image when retrieving the image at URL.
  40. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  41. - parameter progressBlock: Called when the image downloading progress gets updated.
  42. - parameter completionHandler: Called when the image retrieved and set.
  43. - returns: A task represents the retrieving process.
  44. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
  45. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
  46. */
  47. @discardableResult
  48. public func setImage(with resource: Resource?,
  49. placeholder: Image? = nil,
  50. options: KingfisherOptionsInfo? = nil,
  51. progressBlock: DownloadProgressBlock? = nil,
  52. completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
  53. {
  54. guard let resource = resource else {
  55. base.image = placeholder
  56. completionHandler?(nil, nil, .none, nil)
  57. return .empty
  58. }
  59. var options = options ?? KingfisherEmptyOptionsInfo
  60. if !options.keepCurrentImageWhileLoading {
  61. base.image = placeholder
  62. }
  63. let maybeIndicator = indicator
  64. maybeIndicator?.startAnimatingView()
  65. setWebURL(resource.downloadURL)
  66. if base.shouldPreloadAllGIF() {
  67. options.append(.preloadAllGIFData)
  68. }
  69. let task = KingfisherManager.shared.retrieveImage(
  70. with: resource,
  71. options: options,
  72. progressBlock: { receivedSize, totalSize in
  73. if let progressBlock = progressBlock {
  74. progressBlock(receivedSize, totalSize)
  75. }
  76. },
  77. completionHandler: {[weak base] image, error, cacheType, imageURL in
  78. DispatchQueue.main.safeAsync {
  79. guard let strongBase = base, imageURL == self.webURL else {
  80. return
  81. }
  82. self.setImageTask(nil)
  83. guard let image = image else {
  84. maybeIndicator?.stopAnimatingView()
  85. completionHandler?(nil, error, cacheType, imageURL)
  86. return
  87. }
  88. guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)),
  89. case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
  90. {
  91. maybeIndicator?.stopAnimatingView()
  92. strongBase.image = image
  93. completionHandler?(image, error, cacheType, imageURL)
  94. return
  95. }
  96. #if !os(macOS)
  97. UIView.transition(with: strongBase, duration: 0.0, options: [],
  98. animations: { maybeIndicator?.stopAnimatingView() },
  99. completion: { _ in
  100. UIView.transition(with: strongBase, duration: transition.duration,
  101. options: [transition.animationOptions, .allowUserInteraction],
  102. animations: {
  103. // Set image property in the animation.
  104. transition.animations?(strongBase, image)
  105. },
  106. completion: { finished in
  107. transition.completion?(finished)
  108. completionHandler?(image, error, cacheType, imageURL)
  109. })
  110. })
  111. #endif
  112. }
  113. })
  114. setImageTask(task)
  115. return task
  116. }
  117. /**
  118. Cancel the image download task bounded to the image view if it is running.
  119. Nothing will happen if the downloading has already finished.
  120. */
  121. public func cancelDownloadTask() {
  122. imageTask?.downloadTask?.cancel()
  123. }
  124. }
  125. // MARK: - Associated Object
  126. private var lastURLKey: Void?
  127. private var indicatorKey: Void?
  128. private var indicatorTypeKey: Void?
  129. private var imageTaskKey: Void?
  130. extension Kingfisher where Base: ImageView {
  131. /// Get the image URL binded to this image view.
  132. public var webURL: URL? {
  133. return objc_getAssociatedObject(base, &lastURLKey) as? URL
  134. }
  135. fileprivate func setWebURL(_ url: URL) {
  136. objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  137. }
  138. /// Holds which indicator type is going to be used.
  139. /// Default is .none, means no indicator will be shown.
  140. public var indicatorType: IndicatorType {
  141. get {
  142. let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value
  143. return indicator ?? .none
  144. }
  145. set {
  146. switch newValue {
  147. case .none:
  148. indicator = nil
  149. case .activity:
  150. indicator = ActivityIndicator()
  151. case .image(let data):
  152. indicator = ImageIndicator(imageData: data)
  153. case .custom(let anIndicator):
  154. indicator = anIndicator
  155. }
  156. objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  157. }
  158. }
  159. /// Holds any type that conforms to the protocol `Indicator`.
  160. /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
  161. /// It will be `nil` if `indicatorType` is `.none`.
  162. public fileprivate(set) var indicator: Indicator? {
  163. get {
  164. return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value
  165. }
  166. set {
  167. // Remove previous
  168. if let previousIndicator = indicator {
  169. previousIndicator.view.removeFromSuperview()
  170. }
  171. // Add new
  172. if var newIndicator = newValue {
  173. newIndicator.view.frame = base.frame
  174. newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY)
  175. newIndicator.view.isHidden = true
  176. base.addSubview(newIndicator.view)
  177. }
  178. // Save in associated object
  179. objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  180. }
  181. }
  182. fileprivate var imageTask: RetrieveImageTask? {
  183. return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
  184. }
  185. fileprivate func setImageTask(_ task: RetrieveImageTask?) {
  186. objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  187. }
  188. }
  189. // MARK: - Deprecated. Only for back compatibility.
  190. /**
  191. * Set image to use from web. Deprecated. Use `kf` namespacing instead.
  192. */
  193. extension ImageView {
  194. /**
  195. Set an image with a resource, a placeholder image, options, progress handler and completion handler.
  196. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
  197. - parameter placeholder: A placeholder image when retrieving the image at URL.
  198. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  199. - parameter progressBlock: Called when the image downloading progress gets updated.
  200. - parameter completionHandler: Called when the image retrieved and set.
  201. - returns: A task represents the retrieving process.
  202. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
  203. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
  204. */
  205. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage")
  206. @discardableResult
  207. public func kf_setImage(with resource: Resource?,
  208. placeholder: Image? = nil,
  209. options: KingfisherOptionsInfo? = nil,
  210. progressBlock: DownloadProgressBlock? = nil,
  211. completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
  212. {
  213. return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
  214. }
  215. /**
  216. Cancel the image download task bounded to the image view if it is running.
  217. Nothing will happen if the downloading has already finished.
  218. */
  219. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask")
  220. public func kf_cancelDownloadTask() { kf.cancelDownloadTask() }
  221. /// Get the image URL binded to this image view.
  222. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL")
  223. public var kf_webURL: URL? { return kf.webURL }
  224. /// Holds which indicator type is going to be used.
  225. /// Default is .none, means no indicator will be shown.
  226. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType")
  227. public var kf_indicatorType: IndicatorType {
  228. get { return kf.indicatorType }
  229. set { kf.indicatorType = newValue }
  230. }
  231. @available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator")
  232. /// Holds any type that conforms to the protocol `Indicator`.
  233. /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
  234. /// It will be `nil` if `kf_indicatorType` is `.none`.
  235. public private(set) var kf_indicator: Indicator? {
  236. get { return kf.indicator }
  237. set { kf.indicator = newValue }
  238. }
  239. @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask")
  240. fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask }
  241. @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask")
  242. fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) }
  243. @available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL")
  244. fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) }
  245. }
  246. extension ImageView {
  247. func shouldPreloadAllGIF() -> Bool { return true }
  248. }