ImageView+Kingfisher.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. extension KingfisherClass where Base: ImageView {
  32. @discardableResult
  33. public func setImage(with source: Source?,
  34. placeholder: Placeholder? = nil,
  35. options: KingfisherOptionsInfo? = nil,
  36. progressBlock: DownloadProgressBlock? = nil,
  37. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil)
  38. -> DownloadTask?
  39. {
  40. guard let source = source else {
  41. self.placeholder = placeholder
  42. taskIdentifier = nil
  43. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  44. return nil
  45. }
  46. var options = KingfisherManager.shared.defaultOptions + (options ?? .empty)
  47. let noImageOrPlaceholderSet = base.image == nil && self.placeholder == nil
  48. if !options.keepCurrentImageWhileLoading || noImageOrPlaceholderSet {
  49. // Always set placeholder while there is no image/placehoer yet.
  50. self.placeholder = placeholder
  51. }
  52. let maybeIndicator = indicator
  53. maybeIndicator?.startAnimatingView()
  54. taskIdentifier = source.identifier
  55. if base.shouldPreloadAllAnimation() {
  56. options.append(.preloadAllAnimationData)
  57. }
  58. let task = KingfisherManager.shared.retrieveImage(
  59. with: source,
  60. options: options,
  61. progressBlock: { receivedSize, totalSize in
  62. guard source.identifier == self.taskIdentifier else { return }
  63. if let progressBlock = progressBlock {
  64. progressBlock(receivedSize, totalSize)
  65. }
  66. },
  67. completionHandler: { result in
  68. CallbackQueue.mainCurrentOrAsync.execute {
  69. maybeIndicator?.stopAnimatingView()
  70. guard source.identifier == self.taskIdentifier else {
  71. let error = KingfisherError.imageSettingError(
  72. reason: .notCurrentSource(result: result.value, error: result.error, source: source))
  73. completionHandler?(.failure(error))
  74. return
  75. }
  76. self.imageTask = nil
  77. switch result {
  78. case .success(let value):
  79. guard self.needsTransition(options: options, cacheType: value.cacheType) else {
  80. self.placeholder = nil
  81. self.base.image = value.image
  82. completionHandler?(result)
  83. return
  84. }
  85. self.makeTransition(image: value.image, transition: options.transition) {
  86. completionHandler?(result)
  87. }
  88. case .failure:
  89. if let image = options.onFailureImage {
  90. self.base.image = image
  91. }
  92. completionHandler?(result)
  93. }
  94. }
  95. })
  96. imageTask = task
  97. return task
  98. }
  99. /// Sets an image to the image view with a requested resource.
  100. ///
  101. /// - Parameters:
  102. /// - resource: The `Resource` object contains information about the resource.
  103. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  104. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  105. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  106. /// `expectedContentLength`, this block will not be called.
  107. /// - completionHandler: Called when the image retrieved and set finished.
  108. /// - Returns: A task represents the image downloading.
  109. ///
  110. /// - Note:
  111. /// This is the easist way to use Kingfisher to boost the image setting process from network. Since all parameters
  112. /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this:
  113. ///
  114. /// ```
  115. /// let url = URL(string: "https://example.com/image.png")!
  116. /// imageView.kf.setImage(with: URL(string: url))
  117. /// ```
  118. ///
  119. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  120. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  121. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  122. ///
  123. @discardableResult
  124. public func setImage(with resource: Resource?,
  125. placeholder: Placeholder? = nil,
  126. options: KingfisherOptionsInfo? = nil,
  127. progressBlock: DownloadProgressBlock? = nil,
  128. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil)
  129. -> DownloadTask?
  130. {
  131. return setImage(
  132. with: resource.map { .network($0) },
  133. placeholder: placeholder,
  134. options: options,
  135. progressBlock: progressBlock,
  136. completionHandler: completionHandler)
  137. }
  138. /// Cancels the image download task of the image view if it is running.
  139. /// Nothing will happen if the downloading has already finished.
  140. public func cancelDownloadTask() {
  141. imageTask?.cancel()
  142. }
  143. private func needsTransition(options: KingfisherOptionsInfo, cacheType: CacheType) -> Bool {
  144. guard let _ = options.lastMatchIgnoringAssociatedValue(.transition(.none)) else { return false }
  145. if options.forceTransition { return true }
  146. if cacheType == .none { return true }
  147. return false
  148. }
  149. private func makeTransition(image: Image, transition: ImageTransition, done: @escaping () -> Void) {
  150. #if !os(macOS)
  151. // Force hiding the indicator without transition first.
  152. UIView.transition(
  153. with: self.base,
  154. duration: 0.0,
  155. options: [],
  156. animations: { self.indicator?.stopAnimatingView() },
  157. completion: { _ in
  158. self.placeholder = nil
  159. UIView.transition(
  160. with: self.base,
  161. duration: transition.duration,
  162. options: [transition.animationOptions, .allowUserInteraction],
  163. animations: { transition.animations?(self.base, image) },
  164. completion: { finished in
  165. transition.completion?(finished)
  166. done()
  167. }
  168. )
  169. }
  170. )
  171. #else
  172. done()
  173. #endif
  174. }
  175. }
  176. // MARK: - Associated Object
  177. private var taskIdentifierKey: Void?
  178. private var indicatorKey: Void?
  179. private var indicatorTypeKey: Void?
  180. private var placeholderKey: Void?
  181. private var imageTaskKey: Void?
  182. extension KingfisherClass where Base: ImageView {
  183. public private(set) var taskIdentifier: String? {
  184. get { return getAssociatedObject(base, &taskIdentifierKey) }
  185. set { setRetainedAssociatedObject(base, &taskIdentifierKey, newValue) }
  186. }
  187. /// Holds which indicator type is going to be used.
  188. /// Default is `.none`, means no indicator will be shown while downloading.
  189. public var indicatorType: IndicatorType {
  190. get {
  191. return getAssociatedObject(base, &indicatorTypeKey) ?? .none
  192. }
  193. set {
  194. switch newValue {
  195. case .none: indicator = nil
  196. case .activity: indicator = ActivityIndicator()
  197. case .image(let data): indicator = ImageIndicator(imageData: data)
  198. case .custom(let anIndicator): indicator = anIndicator
  199. }
  200. setRetainedAssociatedObject(base, &indicatorTypeKey, newValue)
  201. }
  202. }
  203. /// Holds any type that conforms to the protocol `Indicator`.
  204. /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
  205. /// It will be `nil` if `indicatorType` is `.none`.
  206. public private(set) var indicator: Indicator? {
  207. get {
  208. let box: Box<Indicator>? = getAssociatedObject(base, &indicatorKey)
  209. return box?.value
  210. }
  211. set {
  212. // Remove previous
  213. if let previousIndicator = indicator {
  214. previousIndicator.view.removeFromSuperview()
  215. }
  216. // Add new
  217. if let newIndicator = newValue {
  218. // Set default indicator layout
  219. let view = newIndicator.view
  220. base.addSubview(view)
  221. view.translatesAutoresizingMaskIntoConstraints = false
  222. view.centerXAnchor.constraint(
  223. equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true
  224. view.centerYAnchor.constraint(
  225. equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true
  226. newIndicator.view.isHidden = true
  227. }
  228. // Save in associated object
  229. // Wrap newValue with Box to workaround an issue that Swift does not recognize
  230. // and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
  231. setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init))
  232. }
  233. }
  234. private var imageTask: DownloadTask? {
  235. get { return getAssociatedObject(base, &imageTaskKey) }
  236. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  237. }
  238. /// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while
  239. /// it is downloading an image.
  240. public private(set) var placeholder: Placeholder? {
  241. get { return getAssociatedObject(base, &placeholderKey) }
  242. set {
  243. if let previousPlaceholder = placeholder {
  244. previousPlaceholder.remove(from: base)
  245. }
  246. if let newPlaceholder = newValue {
  247. newPlaceholder.add(to: base)
  248. } else {
  249. base.image = nil
  250. }
  251. setRetainedAssociatedObject(base, &placeholderKey, newValue)
  252. }
  253. }
  254. }
  255. @objc extension ImageView {
  256. func shouldPreloadAllAnimation() -> Bool { return true }
  257. }
  258. extension KingfisherClass where Base: ImageView {
  259. /// Gets the image URL binded to this image view.
  260. @available(*, deprecated, message: "Use `taskIdentifier` instead.", renamed: "taskIdentifier")
  261. public private(set) var webURL: URL? {
  262. get { return taskIdentifier.flatMap { URL(string: $0) } }
  263. set { taskIdentifier = newValue?.absoluteString }
  264. }
  265. }