ImageBinder.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. //
  2. // ImageBinder.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2019/06/27.
  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 canImport(SwiftUI) && canImport(Combine)
  27. import SwiftUI
  28. import Combine
  29. @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
  30. extension KFImage {
  31. /// Represents a binder for `KFImage`. It takes responsibility as an `ObjectBinding` and performs
  32. /// image downloading and progress reporting based on `KingfisherManager`.
  33. class ImageBinder: ObservableObject {
  34. init() {}
  35. var downloadTask: DownloadTask?
  36. private var loading = false
  37. var loadingOrSucceeded: Bool {
  38. return loading || loadedImage != nil
  39. }
  40. // Do not use @Published due to https://github.com/onevcat/Kingfisher/issues/1717. Revert to @Published once
  41. // we can drop iOS 12.
  42. private(set) var loaded = false
  43. private(set) var animating = false
  44. var loadedImage: KFCrossPlatformImage? = nil { willSet { objectWillChange.send() } }
  45. var progress: Progress = .init()
  46. func markLoading() {
  47. loading = true
  48. }
  49. func markLoaded(sendChangeEvent: Bool) {
  50. loaded = true
  51. if sendChangeEvent {
  52. objectWillChange.send()
  53. }
  54. }
  55. func start<HoldingView: KFImageHoldingView>(context: Context<HoldingView>) {
  56. guard let source = context.source else {
  57. CallbackQueue.mainCurrentOrAsync.execute {
  58. context.onFailureDelegate.call(KingfisherError.imageSettingError(reason: .emptySource))
  59. if let image = context.options.onFailureImage {
  60. self.loadedImage = image
  61. }
  62. self.loading = false
  63. self.markLoaded(sendChangeEvent: false)
  64. }
  65. return
  66. }
  67. loading = true
  68. progress = .init()
  69. downloadTask = KingfisherManager.shared
  70. .retrieveImage(
  71. with: source,
  72. options: context.options,
  73. progressBlock: { size, total in
  74. self.updateProgress(downloaded: size, total: total)
  75. context.onProgressDelegate.call((size, total))
  76. },
  77. completionHandler: { [weak self] result in
  78. guard let self = self else { return }
  79. CallbackQueue.mainCurrentOrAsync.execute {
  80. self.downloadTask = nil
  81. self.loading = false
  82. }
  83. switch result {
  84. case .success(let value):
  85. CallbackQueue.mainCurrentOrAsync.execute {
  86. if let fadeDuration = context.fadeTransitionDuration(cacheType: value.cacheType) {
  87. self.animating = true
  88. let animation = Animation.linear(duration: fadeDuration)
  89. withAnimation(animation) {
  90. // Trigger the view render to apply the animation.
  91. self.markLoaded(sendChangeEvent: true)
  92. }
  93. } else {
  94. self.markLoaded(sendChangeEvent: false)
  95. }
  96. self.loadedImage = value.image
  97. self.animating = false
  98. }
  99. CallbackQueue.mainAsync.execute {
  100. context.onSuccessDelegate.call(value)
  101. }
  102. case .failure(let error):
  103. CallbackQueue.mainCurrentOrAsync.execute {
  104. if let image = context.options.onFailureImage {
  105. self.loadedImage = image
  106. }
  107. self.markLoaded(sendChangeEvent: true)
  108. }
  109. CallbackQueue.mainAsync.execute {
  110. context.onFailureDelegate.call(error)
  111. }
  112. }
  113. })
  114. }
  115. private func updateProgress(downloaded: Int64, total: Int64) {
  116. progress.totalUnitCount = total
  117. progress.completedUnitCount = downloaded
  118. objectWillChange.send()
  119. }
  120. /// Cancels the download task if it is in progress.
  121. func cancel() {
  122. downloadTask?.cancel()
  123. downloadTask = nil
  124. loading = false
  125. }
  126. }
  127. }
  128. #endif