ImageView+Kingfisher.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. //
  2. // ImageView+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  6. //
  7. // Copyright (c) 2018 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. If `resource` is `nil`, the `placeholder` image will be set and
  47. `completionHandler` will be called with both `error` and `image` being `nil`.
  48. */
  49. @discardableResult
  50. public func setImage(with resource: Resource?,
  51. placeholder: Placeholder? = nil,
  52. options: KingfisherOptionsInfo? = nil,
  53. progressBlock: DownloadProgressBlock? = nil,
  54. completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
  55. {
  56. guard let resource = resource else {
  57. self.placeholder = placeholder
  58. setWebURL(nil)
  59. completionHandler?(nil, nil, .none, nil)
  60. return .empty
  61. }
  62. var options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo)
  63. let noImageOrPlaceholderSet = base.image == nil && self.placeholder == nil
  64. if !options.keepCurrentImageWhileLoading || noImageOrPlaceholderSet { // Always set placeholder while there is no image/placehoer yet.
  65. self.placeholder = placeholder
  66. }
  67. let maybeIndicator = indicator
  68. maybeIndicator?.startAnimatingView()
  69. setWebURL(resource.downloadURL)
  70. if base.shouldPreloadAllAnimation() {
  71. options.append(.preloadAllAnimationData)
  72. }
  73. let task = KingfisherManager.shared.retrieveImage(
  74. with: resource,
  75. options: options,
  76. progressBlock: { receivedSize, totalSize in
  77. guard resource.downloadURL == self.webURL else {
  78. return
  79. }
  80. if let progressBlock = progressBlock {
  81. progressBlock(receivedSize, totalSize)
  82. }
  83. },
  84. completionHandler: {[weak base] image, error, cacheType, imageURL in
  85. DispatchQueue.main.safeAsync {
  86. maybeIndicator?.stopAnimatingView()
  87. guard let strongBase = base, imageURL == self.webURL else {
  88. completionHandler?(image, error, cacheType, imageURL)
  89. return
  90. }
  91. self.setImageTask(nil)
  92. guard let image = image else {
  93. completionHandler?(nil, error, cacheType, imageURL)
  94. return
  95. }
  96. guard let transitionItem = options.lastMatchIgnoringAssociatedValue(.transition(.none)),
  97. case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
  98. {
  99. self.placeholder = nil
  100. strongBase.image = image
  101. completionHandler?(image, error, cacheType, imageURL)
  102. return
  103. }
  104. #if !os(macOS)
  105. UIView.transition(with: strongBase, duration: 0.0, options: [],
  106. animations: { maybeIndicator?.stopAnimatingView() },
  107. completion: { _ in
  108. self.placeholder = nil
  109. UIView.transition(with: strongBase, duration: transition.duration,
  110. options: [transition.animationOptions, .allowUserInteraction],
  111. animations: {
  112. // Set image property in the animation.
  113. transition.animations?(strongBase, image)
  114. },
  115. completion: { finished in
  116. transition.completion?(finished)
  117. completionHandler?(image, error, cacheType, imageURL)
  118. })
  119. })
  120. #endif
  121. }
  122. })
  123. setImageTask(task)
  124. return task
  125. }
  126. /**
  127. Cancel the image download task bounded to the image view if it is running.
  128. Nothing will happen if the downloading has already finished.
  129. */
  130. public func cancelDownloadTask() {
  131. imageTask?.cancel()
  132. }
  133. }
  134. // MARK: - Associated Object
  135. private var lastURLKey: Void?
  136. private var indicatorKey: Void?
  137. private var indicatorTypeKey: Void?
  138. private var placeholderKey: Void?
  139. private var imageTaskKey: Void?
  140. extension Kingfisher where Base: ImageView {
  141. /// Get the image URL binded to this image view.
  142. public var webURL: URL? {
  143. return objc_getAssociatedObject(base, &lastURLKey) as? URL
  144. }
  145. fileprivate func setWebURL(_ url: URL?) {
  146. objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  147. }
  148. /// Holds which indicator type is going to be used.
  149. /// Default is .none, means no indicator will be shown.
  150. public var indicatorType: IndicatorType {
  151. get {
  152. let indicator = objc_getAssociatedObject(base, &indicatorTypeKey) as? IndicatorType
  153. return indicator ?? .none
  154. }
  155. set {
  156. switch newValue {
  157. case .none:
  158. indicator = nil
  159. case .activity:
  160. indicator = ActivityIndicator()
  161. case .image(let data):
  162. indicator = ImageIndicator(imageData: data)
  163. case .custom(let anIndicator):
  164. indicator = anIndicator
  165. }
  166. objc_setAssociatedObject(base, &indicatorTypeKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  167. }
  168. }
  169. /// Holds any type that conforms to the protocol `Indicator`.
  170. /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
  171. /// It will be `nil` if `indicatorType` is `.none`.
  172. public fileprivate(set) var indicator: Indicator? {
  173. get {
  174. guard let box = objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator> else {
  175. return nil
  176. }
  177. return box.value
  178. }
  179. set {
  180. // Remove previous
  181. if let previousIndicator = indicator {
  182. previousIndicator.view.removeFromSuperview()
  183. }
  184. // Add new
  185. if var newIndicator = newValue {
  186. // Set default indicator frame if the view's frame not set.
  187. if newIndicator.view.frame == .zero {
  188. newIndicator.view.frame = base.frame
  189. }
  190. newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY)
  191. newIndicator.view.isHidden = true
  192. base.addSubview(newIndicator.view)
  193. }
  194. // Save in associated object
  195. // Wrap newValue with Box to workaround an issue that Swift does not recognize
  196. // and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
  197. objc_setAssociatedObject(base, &indicatorKey, newValue.map(Box.init), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  198. }
  199. }
  200. fileprivate var imageTask: RetrieveImageTask? {
  201. return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
  202. }
  203. fileprivate func setImageTask(_ task: RetrieveImageTask?) {
  204. objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  205. }
  206. public fileprivate(set) var placeholder: Placeholder? {
  207. get {
  208. return objc_getAssociatedObject(base, &placeholderKey) as? Placeholder
  209. }
  210. set {
  211. if let previousPlaceholder = placeholder {
  212. previousPlaceholder.remove(from: base)
  213. }
  214. if let newPlaceholder = newValue {
  215. newPlaceholder.add(to: base)
  216. } else {
  217. base.image = nil
  218. }
  219. objc_setAssociatedObject(base, &placeholderKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  220. }
  221. }
  222. }
  223. @objc extension ImageView {
  224. func shouldPreloadAllAnimation() -> Bool { return true }
  225. }