ImageView+Kingfisher.swift 17 KB

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