ImageView+Kingfisher.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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. let task = KingfisherManager.shared.retrieveImage(
  297. with: source,
  298. options: options,
  299. downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
  300. progressiveImageSetter: { self.base.image = $0 },
  301. referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
  302. completionHandler: { result in
  303. CallbackQueue.mainCurrentOrAsync.execute {
  304. maybeIndicator?.stopAnimatingView()
  305. guard issuedIdentifier == self.taskIdentifier else {
  306. let reason: KingfisherError.ImageSettingErrorReason
  307. do {
  308. let value = try result.get()
  309. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  310. } catch {
  311. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  312. }
  313. let error = KingfisherError.imageSettingError(reason: reason)
  314. completionHandler?(.failure(error))
  315. return
  316. }
  317. mutatingSelf.imageTask = nil
  318. mutatingSelf.taskIdentifier = nil
  319. switch result {
  320. case .success(let value):
  321. guard self.needsTransition(options: options, cacheType: value.cacheType) else {
  322. mutatingSelf.placeholder = nil
  323. self.base.image = value.image
  324. completionHandler?(result)
  325. return
  326. }
  327. self.makeTransition(image: value.image, transition: options.transition) {
  328. completionHandler?(result)
  329. }
  330. case .failure:
  331. if let image = options.onFailureImage {
  332. mutatingSelf.placeholder = nil
  333. self.base.image = image
  334. }
  335. completionHandler?(result)
  336. }
  337. }
  338. }
  339. )
  340. mutatingSelf.imageTask = task
  341. return task
  342. }
  343. // MARK: Cancelling Downloading Task
  344. /// Cancels the image download task of the image view if it is running.
  345. /// Nothing will happen if the downloading has already finished.
  346. public func cancelDownloadTask() {
  347. imageTask?.cancel()
  348. }
  349. private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool {
  350. switch options.transition {
  351. case .none:
  352. return false
  353. #if os(macOS)
  354. case .fade: // Fade is only a placeholder for SwiftUI on macOS.
  355. return false
  356. #else
  357. default:
  358. if options.forceTransition { return true }
  359. if cacheType == .none { return true }
  360. return false
  361. #endif
  362. }
  363. }
  364. private func makeTransition(image: KFCrossPlatformImage, transition: ImageTransition, done: @escaping () -> Void) {
  365. #if !os(macOS)
  366. // Force hiding the indicator without transition first.
  367. UIView.transition(
  368. with: self.base,
  369. duration: 0.0,
  370. options: [],
  371. animations: { self.indicator?.stopAnimatingView() },
  372. completion: { _ in
  373. var mutatingSelf = self
  374. mutatingSelf.placeholder = nil
  375. UIView.transition(
  376. with: self.base,
  377. duration: transition.duration,
  378. options: [transition.animationOptions, .allowUserInteraction],
  379. animations: { transition.animations?(self.base, image) },
  380. completion: { finished in
  381. transition.completion?(finished)
  382. done()
  383. }
  384. )
  385. }
  386. )
  387. #else
  388. done()
  389. #endif
  390. }
  391. }
  392. // MARK: - Associated Object
  393. private var taskIdentifierKey: Void?
  394. private var indicatorKey: Void?
  395. private var indicatorTypeKey: Void?
  396. private var placeholderKey: Void?
  397. private var imageTaskKey: Void?
  398. extension KingfisherWrapper where Base: KFCrossPlatformImageView {
  399. // MARK: Properties
  400. public private(set) var taskIdentifier: Source.Identifier.Value? {
  401. get {
  402. let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
  403. return box?.value
  404. }
  405. set {
  406. let box = newValue.map { Box($0) }
  407. setRetainedAssociatedObject(base, &taskIdentifierKey, box)
  408. }
  409. }
  410. /// Holds which indicator type is going to be used.
  411. /// Default is `.none`, means no indicator will be shown while downloading.
  412. public var indicatorType: IndicatorType {
  413. get {
  414. return getAssociatedObject(base, &indicatorTypeKey) ?? .none
  415. }
  416. set {
  417. switch newValue {
  418. case .none: indicator = nil
  419. case .activity: indicator = ActivityIndicator()
  420. case .image(let data): indicator = ImageIndicator(imageData: data)
  421. case .custom(let anIndicator): indicator = anIndicator
  422. }
  423. setRetainedAssociatedObject(base, &indicatorTypeKey, newValue)
  424. }
  425. }
  426. /// Holds any type that conforms to the protocol `Indicator`.
  427. /// The protocol `Indicator` has a `view` property that will be shown when loading an image.
  428. /// It will be `nil` if `indicatorType` is `.none`.
  429. public private(set) var indicator: Indicator? {
  430. get {
  431. let box: Box<Indicator>? = getAssociatedObject(base, &indicatorKey)
  432. return box?.value
  433. }
  434. set {
  435. // Remove previous
  436. if let previousIndicator = indicator {
  437. previousIndicator.view.removeFromSuperview()
  438. }
  439. // Add new
  440. if let newIndicator = newValue {
  441. // Set default indicator layout
  442. let view = newIndicator.view
  443. base.addSubview(view)
  444. view.translatesAutoresizingMaskIntoConstraints = false
  445. view.centerXAnchor.constraint(
  446. equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true
  447. view.centerYAnchor.constraint(
  448. equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true
  449. switch newIndicator.sizeStrategy(in: base) {
  450. case .intrinsicSize:
  451. break
  452. case .full:
  453. view.heightAnchor.constraint(equalTo: base.heightAnchor, constant: 0).isActive = true
  454. view.widthAnchor.constraint(equalTo: base.widthAnchor, constant: 0).isActive = true
  455. case .size(let size):
  456. view.heightAnchor.constraint(equalToConstant: size.height).isActive = true
  457. view.widthAnchor.constraint(equalToConstant: size.width).isActive = true
  458. }
  459. newIndicator.view.isHidden = true
  460. }
  461. // Save in associated object
  462. // Wrap newValue with Box to workaround an issue that Swift does not recognize
  463. // and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872
  464. setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init))
  465. }
  466. }
  467. private var imageTask: DownloadTask? {
  468. get { return getAssociatedObject(base, &imageTaskKey) }
  469. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  470. }
  471. /// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while
  472. /// it is downloading an image.
  473. public private(set) var placeholder: Placeholder? {
  474. get { return getAssociatedObject(base, &placeholderKey) }
  475. set {
  476. if let previousPlaceholder = placeholder {
  477. previousPlaceholder.remove(from: base)
  478. }
  479. if let newPlaceholder = newValue {
  480. newPlaceholder.add(to: base)
  481. } else {
  482. base.image = nil
  483. }
  484. setRetainedAssociatedObject(base, &placeholderKey, newValue)
  485. }
  486. }
  487. }
  488. extension KFCrossPlatformImageView {
  489. @objc func shouldPreloadAllAnimation() -> Bool { return true }
  490. }
  491. #endif