ImageView+Kingfisher.swift 23 KB

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