ImageView+Kingfisher.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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(watchOS)
  27. #if os(macOS)
  28. import AppKit
  29. #else
  30. import UIKit
  31. #endif
  32. extension KingfisherWrapper where Base: KFCrossPlatformImageView {
  33. // MARK: Setting Image
  34. /// Sets an image to the image view with a `Source`.
  35. ///
  36. /// - Parameters:
  37. /// - source: The `Source` object defines data information from network or a data provider.
  38. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  39. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  40. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  41. /// `expectedContentLength`, this block will not be called.
  42. /// - completionHandler: Called when the image retrieved and set finished.
  43. /// - Returns: A task represents the image downloading.
  44. ///
  45. /// - Note:
  46. /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
  47. /// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
  48. ///
  49. /// ```
  50. /// // Set image from a network source.
  51. /// let url = URL(string: "https://example.com/image.png")!
  52. /// imageView.kf.setImage(with: .network(url))
  53. ///
  54. /// // Or set image from a data provider.
  55. /// let provider = LocalFileImageDataProvider(fileURL: fileURL)
  56. /// imageView.kf.setImage(with: .provider(provider))
  57. /// ```
  58. ///
  59. /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code
  60. /// above is equivalent to:
  61. ///
  62. /// ```
  63. /// imageView.kf.setImage(with: url)
  64. /// imageView.kf.setImage(with: provider)
  65. /// ```
  66. ///
  67. /// Internally, this method will use `KingfisherManager` to get the source.
  68. /// Since this method will perform UI changes, you must call it from the main thread.
  69. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  70. ///
  71. @discardableResult
  72. public func setImage(
  73. with source: Source?,
  74. placeholder: Placeholder? = nil,
  75. options: KingfisherOptionsInfo? = nil,
  76. progressBlock: DownloadProgressBlock? = nil,
  77. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  78. {
  79. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  80. return setImage(with: source, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: completionHandler)
  81. }
  82. /// Sets an image to the image view with a `Source`.
  83. ///
  84. /// - Parameters:
  85. /// - source: The `Source` object defines data information from network or a data provider.
  86. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  87. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  88. /// - completionHandler: Called when the image retrieved and set finished.
  89. /// - Returns: A task represents the image downloading.
  90. ///
  91. /// - Note:
  92. /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters
  93. /// have a default value except the `source`, you can set an image from a certain URL to an image view like this:
  94. ///
  95. /// ```
  96. /// // Set image from a network source.
  97. /// let url = URL(string: "https://example.com/image.png")!
  98. /// imageView.kf.setImage(with: .network(url))
  99. ///
  100. /// // Or set image from a data provider.
  101. /// let provider = LocalFileImageDataProvider(fileURL: fileURL)
  102. /// imageView.kf.setImage(with: .provider(provider))
  103. /// ```
  104. ///
  105. /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code
  106. /// above is equivalent to:
  107. ///
  108. /// ```
  109. /// imageView.kf.setImage(with: url)
  110. /// imageView.kf.setImage(with: provider)
  111. /// ```
  112. ///
  113. /// Internally, this method will use `KingfisherManager` to get the source.
  114. /// Since this method will perform UI changes, you must call it from the main thread.
  115. /// The `completionHandler` will be also executed in the main thread.
  116. ///
  117. @discardableResult
  118. public func setImage(
  119. with source: Source?,
  120. placeholder: Placeholder? = nil,
  121. options: KingfisherOptionsInfo? = nil,
  122. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  123. {
  124. return setImage(
  125. with: source,
  126. placeholder: placeholder,
  127. options: options,
  128. progressBlock: nil,
  129. completionHandler: completionHandler
  130. )
  131. }
  132. /// Sets an image to the image view with a requested resource.
  133. ///
  134. /// - Parameters:
  135. /// - resource: The `Resource` object contains information about the resource.
  136. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  137. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  138. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  139. /// `expectedContentLength`, this block will not be called.
  140. /// - completionHandler: Called when the image retrieved and set finished.
  141. /// - Returns: A task represents the image downloading.
  142. ///
  143. /// - Note:
  144. /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters
  145. /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this:
  146. ///
  147. /// ```
  148. /// let url = URL(string: "https://example.com/image.png")!
  149. /// imageView.kf.setImage(with: url)
  150. /// ```
  151. ///
  152. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  153. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  154. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  155. ///
  156. @discardableResult
  157. public func setImage(
  158. with resource: Resource?,
  159. placeholder: Placeholder? = nil,
  160. options: KingfisherOptionsInfo? = nil,
  161. progressBlock: DownloadProgressBlock? = nil,
  162. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  163. {
  164. return setImage(
  165. with: resource?.convertToSource(),
  166. placeholder: placeholder,
  167. options: options,
  168. progressBlock: progressBlock,
  169. completionHandler: completionHandler)
  170. }
  171. /// Sets an image to the image view with a requested resource.
  172. ///
  173. /// - Parameters:
  174. /// - resource: The `Resource` object contains information about the resource.
  175. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  176. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  177. /// - completionHandler: Called when the image retrieved and set finished.
  178. /// - Returns: A task represents the image downloading.
  179. ///
  180. /// - Note:
  181. /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters
  182. /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this:
  183. ///
  184. /// ```
  185. /// let url = URL(string: "https://example.com/image.png")!
  186. /// imageView.kf.setImage(with: url)
  187. /// ```
  188. ///
  189. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  190. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  191. /// The `completionHandler` will be also executed in the main thread.
  192. ///
  193. @discardableResult
  194. public func setImage(
  195. with resource: Resource?,
  196. placeholder: Placeholder? = nil,
  197. options: KingfisherOptionsInfo? = nil,
  198. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  199. {
  200. return setImage(
  201. with: resource,
  202. placeholder: placeholder,
  203. options: options,
  204. progressBlock: nil,
  205. completionHandler: completionHandler
  206. )
  207. }
  208. /// Sets an image to the image view with a data provider.
  209. ///
  210. /// - Parameters:
  211. /// - provider: The `ImageDataProvider` object contains information about the data.
  212. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  213. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  214. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  215. /// `expectedContentLength`, this block will not be called.
  216. /// - completionHandler: Called when the image retrieved and set finished.
  217. /// - Returns: A task represents the image downloading.
  218. ///
  219. /// Internally, this method will use `KingfisherManager` to get the image data, from either cache
  220. /// or the data provider. Since this method will perform UI changes, you must call it from the main thread.
  221. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  222. ///
  223. @discardableResult
  224. public func setImage(
  225. with provider: ImageDataProvider?,
  226. placeholder: Placeholder? = nil,
  227. options: KingfisherOptionsInfo? = nil,
  228. progressBlock: DownloadProgressBlock? = nil,
  229. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  230. {
  231. return setImage(
  232. with: provider.map { .provider($0) },
  233. placeholder: placeholder,
  234. options: options,
  235. progressBlock: progressBlock,
  236. completionHandler: completionHandler)
  237. }
  238. /// Sets an image to the image view with a data provider.
  239. ///
  240. /// - Parameters:
  241. /// - provider: The `ImageDataProvider` object contains information about the data.
  242. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  243. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  244. /// - completionHandler: Called when the image retrieved and set finished.
  245. /// - Returns: A task represents the image downloading.
  246. ///
  247. /// Internally, this method will use `KingfisherManager` to get the image data, from either cache
  248. /// or the data provider. Since this method will perform UI changes, you must call it from the main thread.
  249. /// The `completionHandler` will be also executed in the main thread.
  250. ///
  251. @discardableResult
  252. public func setImage(
  253. with provider: ImageDataProvider?,
  254. placeholder: Placeholder? = nil,
  255. options: KingfisherOptionsInfo? = nil,
  256. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  257. {
  258. return setImage(
  259. with: provider,
  260. placeholder: placeholder,
  261. options: options,
  262. progressBlock: nil,
  263. completionHandler: completionHandler
  264. )
  265. }
  266. func setImage(
  267. with source: Source?,
  268. placeholder: Placeholder? = nil,
  269. parsedOptions: KingfisherParsedOptionsInfo,
  270. progressBlock: DownloadProgressBlock? = nil,
  271. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  272. {
  273. var mutatingSelf = self
  274. guard let source = source else {
  275. mutatingSelf.placeholder = placeholder
  276. mutatingSelf.taskIdentifier = nil
  277. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  278. return nil
  279. }
  280. var options = parsedOptions
  281. let isEmptyImage = base.image == nil && self.placeholder == nil
  282. if !options.keepCurrentImageWhileLoading || isEmptyImage {
  283. // Always set placeholder while there is no image/placeholder yet.
  284. mutatingSelf.placeholder = placeholder
  285. }
  286. let maybeIndicator = indicator
  287. maybeIndicator?.startAnimatingView()
  288. let issuedIdentifier = Source.Identifier.next()
  289. mutatingSelf.taskIdentifier = issuedIdentifier
  290. if base.shouldPreloadAllAnimation() {
  291. options.preloadAllAnimationData = true
  292. }
  293. if let block = progressBlock {
  294. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  295. }
  296. if let provider = ImageProgressiveProvider(options, refresh: { image in
  297. self.base.image = image
  298. }) {
  299. options.onDataReceived = (options.onDataReceived ?? []) + [provider]
  300. }
  301. options.onDataReceived?.forEach {
  302. $0.onShouldApply = { issuedIdentifier == self.taskIdentifier }
  303. }
  304. let task = KingfisherManager.shared.retrieveImage(
  305. with: source,
  306. options: options,
  307. downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
  308. completionHandler: { result in
  309. CallbackQueue.mainCurrentOrAsync.execute {
  310. maybeIndicator?.stopAnimatingView()
  311. guard issuedIdentifier == self.taskIdentifier else {
  312. let reason: KingfisherError.ImageSettingErrorReason
  313. do {
  314. let value = try result.get()
  315. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  316. } catch {
  317. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  318. }
  319. let error = KingfisherError.imageSettingError(reason: reason)
  320. completionHandler?(.failure(error))
  321. return
  322. }
  323. mutatingSelf.imageTask = nil
  324. mutatingSelf.taskIdentifier = nil
  325. switch result {
  326. case .success(let value):
  327. guard self.needsTransition(options: options, cacheType: value.cacheType) else {
  328. mutatingSelf.placeholder = nil
  329. self.base.image = value.image
  330. completionHandler?(result)
  331. return
  332. }
  333. self.makeTransition(image: value.image, transition: options.transition) {
  334. completionHandler?(result)
  335. }
  336. case .failure:
  337. if let image = options.onFailureImage {
  338. self.base.image = image
  339. }
  340. completionHandler?(result)
  341. }
  342. }
  343. }
  344. )
  345. mutatingSelf.imageTask = task
  346. return task
  347. }
  348. // MARK: Cancelling Downloading Task
  349. /// Cancels the image download task of the image view if it is running.
  350. /// Nothing will happen if the downloading has already finished.
  351. public func cancelDownloadTask() {
  352. imageTask?.cancel()
  353. }
  354. private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool {
  355. switch options.transition {
  356. case .none:
  357. return false
  358. #if os(macOS)
  359. case .fade: // Fade is only a placeholder for SwiftUI on macOS.
  360. return false
  361. #else
  362. default:
  363. if options.forceTransition { return true }
  364. if cacheType == .none { return true }
  365. return false
  366. #endif
  367. }
  368. }
  369. private func makeTransition(image: KFCrossPlatformImage, transition: ImageTransition, done: @escaping () -> Void) {
  370. #if !os(macOS)
  371. // Force hiding the indicator without transition first.
  372. UIView.transition(
  373. with: self.base,
  374. duration: 0.0,
  375. options: [],
  376. animations: { self.indicator?.stopAnimatingView() },
  377. completion: { _ in
  378. var mutatingSelf = self
  379. mutatingSelf.placeholder = nil
  380. UIView.transition(
  381. with: self.base,
  382. duration: transition.duration,
  383. options: [transition.animationOptions, .allowUserInteraction],
  384. animations: { transition.animations?(self.base, image) },
  385. completion: { finished in
  386. transition.completion?(finished)
  387. done()
  388. }
  389. )
  390. }
  391. )
  392. #else
  393. done()
  394. #endif
  395. }
  396. }
  397. // MARK: - Associated Object
  398. private var taskIdentifierKey: Void?
  399. private var indicatorKey: Void?
  400. private var indicatorTypeKey: Void?
  401. private var placeholderKey: Void?
  402. private var imageTaskKey: Void?
  403. extension KingfisherWrapper where Base: KFCrossPlatformImageView {
  404. // MARK: Properties
  405. public private(set) var taskIdentifier: Source.Identifier.Value? {
  406. get {
  407. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  408. return box?.value
  409. }
  410. set {
  411. let box = newValue.map { Box($0) }
  412. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  413. }
  414. }
  415. /// Holds which indicator type is going to be used.
  416. /// Default is `.none`, means no indicator will be shown while downloading.
  417. public var indicatorType: IndicatorType {
  418. get {
  419. return getAssociatedObject(base, &indicatorTypeKey) ?? .none
  420. }
  421. set {
  422. switch newValue {
  423. case .none: indicator = nil
  424. case .activity: indicator = ActivityIndicator()
  425. case .image(let data): indicator = ImageIndicator(imageData: data)
  426. case .custom(let anIndicator): indicator = anIndicator
  427. }
  428. setRetainedAssociatedObject(base, &indicatorTypeKey, newValue)
  429. }
  430. }
  431. /// Holds any type that conforms to the protocol `Indicator`.
  432. /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
  433. /// It will be `nil` if `indicatorType` is `.none`.
  434. public private(set) var indicator: Indicator? {
  435. get {
  436. let box: Box<Indicator>? = getAssociatedObject(base, &indicatorKey)
  437. return box?.value
  438. }
  439. set {
  440. // Remove previous
  441. if let previousIndicator = indicator {
  442. previousIndicator.view.removeFromSuperview()
  443. }
  444. // Add new
  445. if let newIndicator = newValue {
  446. // Set default indicator layout
  447. let view = newIndicator.view
  448. base.addSubview(view)
  449. view.translatesAutoresizingMaskIntoConstraints = false
  450. view.centerXAnchor.constraint(
  451. equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true
  452. view.centerYAnchor.constraint(
  453. equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true
  454. switch newIndicator.sizeStrategy(in: base) {
  455. case .intrinsicSize:
  456. break
  457. case .full:
  458. view.heightAnchor.constraint(equalTo: base.heightAnchor, constant: 0).isActive = true
  459. view.widthAnchor.constraint(equalTo: base.widthAnchor, constant: 0).isActive = true
  460. case .size(let size):
  461. view.heightAnchor.constraint(equalToConstant: size.height).isActive = true
  462. view.widthAnchor.constraint(equalToConstant: size.width).isActive = true
  463. }
  464. newIndicator.view.isHidden = true
  465. }
  466. // Save in associated object
  467. // Wrap newValue with Box to workaround an issue that Swift does not recognize
  468. // and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
  469. setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init))
  470. }
  471. }
  472. private var imageTask: DownloadTask? {
  473. get { return getAssociatedObject(base, &imageTaskKey) }
  474. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  475. }
  476. /// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while
  477. /// it is downloading an image.
  478. public private(set) var placeholder: Placeholder? {
  479. get { return getAssociatedObject(base, &placeholderKey) }
  480. set {
  481. if let previousPlaceholder = placeholder {
  482. previousPlaceholder.remove(from: base)
  483. }
  484. if let newPlaceholder = newValue {
  485. newPlaceholder.add(to: base)
  486. } else {
  487. base.image = nil
  488. }
  489. setRetainedAssociatedObject(base, &placeholderKey, newValue)
  490. }
  491. }
  492. }
  493. extension KFCrossPlatformImageView {
  494. @objc func shouldPreloadAllAnimation() -> Bool { return true }
  495. }
  496. #endif