ImageView+Kingfisher.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. //
  2. // ImageView+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  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 os(macOS)
  27. import AppKit
  28. #else
  29. import UIKit
  30. #endif
  31. extension KingfisherWrapper where Base: ImageView {
  32. // MARK: Setting Image
  33. /// Sets an image to the image view with a `Source`.
  34. ///
  35. /// - Parameters:
  36. /// - source: The `Source` object defines data information from network or a data provider.
  37. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  38. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  39. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  40. /// `expectedContentLength`, this block will not be called.
  41. /// - completionHandler: Called when the image retrieved and set finished.
  42. /// - Returns: A task represents the image downloading.
  43. ///
  44. /// - Note:
  45. /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
  46. /// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
  47. ///
  48. /// ```
  49. /// // Set image from a network source.
  50. /// let url = URL(string: "https://example.com/image.png")!
  51. /// imageView.kf.setImage(with: .network(url))
  52. ///
  53. /// // Or set image from a data provider.
  54. /// let provider = LocalFileImageDataProvider(fileURL: fileURL)
  55. /// imageView.kf.setImage(with: .provider(provider))
  56. /// ```
  57. ///
  58. /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code
  59. /// above is equivalent to:
  60. ///
  61. /// ```
  62. /// imageView.kf.setImage(with: url)
  63. /// imageView.kf.setImage(with: provider)
  64. /// ```
  65. ///
  66. /// Internally, this method will use `KingfisherManager` to get the source.
  67. /// Since this method will perform UI changes, you must call it from the main thread.
  68. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  69. ///
  70. @discardableResult
  71. public func setImage(
  72. with source: Source?,
  73. placeholder: Placeholder? = nil,
  74. options: KingfisherOptionsInfo? = nil,
  75. progressBlock: DownloadProgressBlock? = nil,
  76. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  77. {
  78. var mutatingSelf = self
  79. guard let source = source else {
  80. mutatingSelf.placeholder = placeholder
  81. mutatingSelf.taskIdentifier = nil
  82. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  83. return nil
  84. }
  85. var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  86. let noImageOrPlaceholderSet = base.image == nil && self.placeholder == nil
  87. if !options.keepCurrentImageWhileLoading || noImageOrPlaceholderSet {
  88. // Always set placeholder while there is no image/placeholder yet.
  89. mutatingSelf.placeholder = placeholder
  90. }
  91. let maybeIndicator = indicator
  92. maybeIndicator?.startAnimatingView()
  93. let issuedIdentifier = Source.Identifier.next()
  94. mutatingSelf.taskIdentifier = issuedIdentifier
  95. if base.shouldPreloadAllAnimation() {
  96. options.preloadAllAnimationData = true
  97. }
  98. if let block = progressBlock {
  99. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  100. }
  101. if let provider = ImageProgressiveProvider(options, refresh: { image in
  102. self.base.image = image
  103. }) {
  104. options.onDataReceived = (options.onDataReceived ?? []) + [provider]
  105. }
  106. options.onDataReceived?.forEach {
  107. $0.onShouldApply = { issuedIdentifier == self.taskIdentifier }
  108. }
  109. let task = KingfisherManager.shared.retrieveImage(
  110. with: source,
  111. options: options,
  112. completionHandler: { result in
  113. CallbackQueue.mainCurrentOrAsync.execute {
  114. maybeIndicator?.stopAnimatingView()
  115. guard issuedIdentifier == self.taskIdentifier else {
  116. let reason: KingfisherError.ImageSettingErrorReason
  117. do {
  118. let value = try result.get()
  119. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  120. } catch {
  121. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  122. }
  123. let error = KingfisherError.imageSettingError(reason: reason)
  124. completionHandler?(.failure(error))
  125. return
  126. }
  127. mutatingSelf.imageTask = nil
  128. mutatingSelf.taskIdentifier = nil
  129. switch result {
  130. case .success(let value):
  131. guard self.needsTransition(options: options, cacheType: value.cacheType) else {
  132. mutatingSelf.placeholder = nil
  133. self.base.image = value.image
  134. completionHandler?(result)
  135. return
  136. }
  137. self.makeTransition(image: value.image, transition: options.transition) {
  138. completionHandler?(result)
  139. }
  140. case .failure:
  141. if let image = options.onFailureImage {
  142. self.base.image = image
  143. }
  144. completionHandler?(result)
  145. }
  146. }
  147. }
  148. )
  149. mutatingSelf.imageTask = task
  150. return task
  151. }
  152. /// Sets an image to the image view with a requested resource.
  153. ///
  154. /// - Parameters:
  155. /// - resource: The `Resource` object contains information about the resource.
  156. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  157. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  158. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  159. /// `expectedContentLength`, this block will not be called.
  160. /// - completionHandler: Called when the image retrieved and set finished.
  161. /// - Returns: A task represents the image downloading.
  162. ///
  163. /// - Note:
  164. /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters
  165. /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this:
  166. ///
  167. /// ```
  168. /// let url = URL(string: "https://example.com/image.png")!
  169. /// imageView.kf.setImage(with: url)
  170. /// ```
  171. ///
  172. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  173. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  174. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  175. ///
  176. @discardableResult
  177. public func setImage(
  178. with resource: Resource?,
  179. placeholder: Placeholder? = nil,
  180. options: KingfisherOptionsInfo? = nil,
  181. progressBlock: DownloadProgressBlock? = nil,
  182. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  183. {
  184. return setImage(
  185. with: resource.map { .network($0) },
  186. placeholder: placeholder,
  187. options: options,
  188. progressBlock: progressBlock,
  189. completionHandler: completionHandler)
  190. }
  191. /// Sets an image to the image view with a data provider.
  192. ///
  193. /// - Parameters:
  194. /// - provider: The `ImageDataProvider` object contains information about the data.
  195. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  196. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  197. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  198. /// `expectedContentLength`, this block will not be called.
  199. /// - completionHandler: Called when the image retrieved and set finished.
  200. /// - Returns: A task represents the image downloading.
  201. ///
  202. /// Internally, this method will use `KingfisherManager` to get the image data, from either cache
  203. /// or the data provider. Since this method will perform UI changes, you must call it from the main thread.
  204. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  205. ///
  206. @discardableResult
  207. public func setImage(
  208. with provider: ImageDataProvider?,
  209. placeholder: Placeholder? = nil,
  210. options: KingfisherOptionsInfo? = nil,
  211. progressBlock: DownloadProgressBlock? = nil,
  212. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  213. {
  214. return setImage(
  215. with: provider.map { .provider($0) },
  216. placeholder: placeholder,
  217. options: options,
  218. progressBlock: progressBlock,
  219. completionHandler: completionHandler)
  220. }
  221. // MARK: Cancelling Downloading Task
  222. /// Cancels the image download task of the image view if it is running.
  223. /// Nothing will happen if the downloading has already finished.
  224. public func cancelDownloadTask() {
  225. imageTask?.cancel()
  226. }
  227. private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool {
  228. switch options.transition {
  229. case .none:
  230. return false
  231. #if !os(macOS)
  232. default:
  233. if options.forceTransition { return true }
  234. if cacheType == .none { return true }
  235. return false
  236. #endif
  237. }
  238. }
  239. private func makeTransition(image: Image, transition: ImageTransition, done: @escaping () -> Void) {
  240. #if !os(macOS)
  241. // Force hiding the indicator without transition first.
  242. UIView.transition(
  243. with: self.base,
  244. duration: 0.0,
  245. options: [],
  246. animations: { self.indicator?.stopAnimatingView() },
  247. completion: { _ in
  248. var mutatingSelf = self
  249. mutatingSelf.placeholder = nil
  250. UIView.transition(
  251. with: self.base,
  252. duration: transition.duration,
  253. options: [transition.animationOptions, .allowUserInteraction],
  254. animations: { transition.animations?(self.base, image) },
  255. completion: { finished in
  256. transition.completion?(finished)
  257. done()
  258. }
  259. )
  260. }
  261. )
  262. #else
  263. done()
  264. #endif
  265. }
  266. }
  267. // MARK: - Associated Object
  268. private var taskIdentifierKey: Void?
  269. private var indicatorKey: Void?
  270. private var indicatorTypeKey: Void?
  271. private var placeholderKey: Void?
  272. private var imageTaskKey: Void?
  273. extension KingfisherWrapper where Base: ImageView {
  274. // MARK: Properties
  275. public private(set) var taskIdentifier: Source.Identifier.Value? {
  276. get {
  277. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  278. return box?.value
  279. }
  280. set {
  281. let box = newValue.map { Box($0) }
  282. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  283. }
  284. }
  285. /// Holds which indicator type is going to be used.
  286. /// Default is `.none`, means no indicator will be shown while downloading.
  287. public var indicatorType: IndicatorType {
  288. get {
  289. return getAssociatedObject(base, &indicatorTypeKey) ?? .none
  290. }
  291. set {
  292. switch newValue {
  293. case .none: indicator = nil
  294. case .activity: indicator = ActivityIndicator()
  295. case .image(let data): indicator = ImageIndicator(imageData: data)
  296. case .custom(let anIndicator): indicator = anIndicator
  297. }
  298. setRetainedAssociatedObject(base, &indicatorTypeKey, newValue)
  299. }
  300. }
  301. /// Holds any type that conforms to the protocol `Indicator`.
  302. /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
  303. /// It will be `nil` if `indicatorType` is `.none`.
  304. public private(set) var indicator: Indicator? {
  305. get {
  306. let box: Box<Indicator>? = getAssociatedObject(base, &indicatorKey)
  307. return box?.value
  308. }
  309. set {
  310. // Remove previous
  311. if let previousIndicator = indicator {
  312. previousIndicator.view.removeFromSuperview()
  313. }
  314. // Add new
  315. if let newIndicator = newValue {
  316. // Set default indicator layout
  317. let view = newIndicator.view
  318. base.addSubview(view)
  319. view.translatesAutoresizingMaskIntoConstraints = false
  320. view.centerXAnchor.constraint(
  321. equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true
  322. view.centerYAnchor.constraint(
  323. equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true
  324. newIndicator.view.isHidden = true
  325. }
  326. // Save in associated object
  327. // Wrap newValue with Box to workaround an issue that Swift does not recognize
  328. // and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
  329. setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init))
  330. }
  331. }
  332. private var imageTask: DownloadTask? {
  333. get { return getAssociatedObject(base, &imageTaskKey) }
  334. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  335. }
  336. /// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while
  337. /// it is downloading an image.
  338. public private(set) var placeholder: Placeholder? {
  339. get { return getAssociatedObject(base, &placeholderKey) }
  340. set {
  341. if let previousPlaceholder = placeholder {
  342. previousPlaceholder.remove(from: base)
  343. }
  344. if let newPlaceholder = newValue {
  345. newPlaceholder.add(to: base)
  346. } else {
  347. base.image = nil
  348. }
  349. setRetainedAssociatedObject(base, &placeholderKey, newValue)
  350. }
  351. }
  352. }
  353. @objc extension ImageView {
  354. func shouldPreloadAllAnimation() -> Bool { return true }
  355. }
  356. extension KingfisherWrapper where Base: ImageView {
  357. /// Gets the image URL bound to this image view.
  358. @available(*, deprecated, message: "Use `taskIdentifier` instead to identify a setting task.")
  359. public private(set) var webURL: URL? {
  360. get { return nil }
  361. set { }
  362. }
  363. }