ImageView+Kingfisher.swift 23 KB

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