ImageBinder.swift 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. @MainActor
  34. class ImageBinder: ObservableObject {
  35. init() {}
  36. var downloadTask: DownloadTask?
  37. private var loading = false
  38. var loadingOrSucceeded: Bool {
  39. return loading || loadedImage != nil
  40. }
  41. // Do not use @Published due to https://github.com/onevcat/Kingfisher/issues/1717. Revert to @Published once
  42. // we can drop iOS 12.
  43. private(set) var loaded = false
  44. private(set) var animating = false
  45. var loadedImage: KFCrossPlatformImage? = nil { willSet { objectWillChange.send() } }
  46. var failureView: (() -> AnyView)? = nil { willSet { objectWillChange.send() } }
  47. var progress: Progress = .init()
  48. func markLoading() {
  49. loading = true
  50. }
  51. func markLoaded(sendChangeEvent: Bool) {
  52. loaded = true
  53. if sendChangeEvent {
  54. objectWillChange.send()
  55. }
  56. }
  57. func start<HoldingView: KFImageHoldingView>(context: Context<HoldingView>) where HoldingView: Sendable {
  58. guard let source = context.source else {
  59. CallbackQueueMain.currentOrAsync {
  60. context.onFailureDelegate.call(KingfisherError.imageSettingError(reason: .emptySource))
  61. if let view = context.failureView {
  62. self.failureView = view
  63. } else if let image = context.options.onFailureImage {
  64. self.loadedImage = image
  65. }
  66. self.loading = false
  67. self.markLoaded(sendChangeEvent: false)
  68. }
  69. return
  70. }
  71. loading = true
  72. progress = .init()
  73. downloadTask = KingfisherManager.shared
  74. .retrieveImage(
  75. with: source,
  76. options: context.options,
  77. progressBlock: { size, total in
  78. self.updateProgress(downloaded: size, total: total)
  79. context.onProgressDelegate.call((size, total))
  80. },
  81. progressiveImageSetter: { image in
  82. CallbackQueueMain.currentOrAsync {
  83. self.markLoaded(sendChangeEvent: true)
  84. self.loadedImage = image
  85. }
  86. },
  87. completionHandler: { [weak self] result in
  88. guard let self else { return }
  89. CallbackQueueMain.currentOrAsync {
  90. self.downloadTask = nil
  91. self.loading = false
  92. }
  93. switch result {
  94. case .success(let value):
  95. CallbackQueueMain.currentOrAsync {
  96. if context.swiftUITransition != nil,
  97. context.shouldApplyFade(cacheType: value.cacheType) {
  98. // Apply SwiftUI loadTransition with custom animation (higher priority than fade)
  99. self.animating = true
  100. let animation = context.swiftUIAnimation ?? .default
  101. withAnimation(animation) {
  102. self.markLoaded(sendChangeEvent: true)
  103. }
  104. } else if let fadeDuration = context.fadeTransitionDuration(cacheType: value.cacheType) {
  105. self.animating = true
  106. let animation = Animation.linear(duration: fadeDuration)
  107. withAnimation(animation) {
  108. // Trigger the view render to apply the animation.
  109. self.markLoaded(sendChangeEvent: true)
  110. }
  111. } else {
  112. self.markLoaded(sendChangeEvent: false)
  113. }
  114. self.loadedImage = value.image
  115. self.animating = false
  116. }
  117. CallbackQueueMain.async {
  118. context.onSuccessDelegate.call(value)
  119. }
  120. case .failure(let error):
  121. CallbackQueueMain.currentOrAsync {
  122. if let view = context.failureView {
  123. self.failureView = view
  124. } else if let image = context.options.onFailureImage {
  125. self.loadedImage = image
  126. }
  127. self.markLoaded(sendChangeEvent: false)
  128. }
  129. CallbackQueueMain.async {
  130. context.onFailureDelegate.call(error)
  131. }
  132. }
  133. })
  134. }
  135. private func updateProgress(downloaded: Int64, total: Int64) {
  136. progress.totalUnitCount = total
  137. progress.completedUnitCount = downloaded
  138. objectWillChange.send()
  139. }
  140. /// Cancels the download task if it is in progress.
  141. func cancel() {
  142. downloadTask?.cancel()
  143. downloadTask = nil
  144. loading = false
  145. }
  146. /// Restores the download task priority to default if it is in progress.
  147. func restorePriorityOnAppear() {
  148. guard let downloadTask = downloadTask, loading == true else { return }
  149. downloadTask.sessionTask?.task.priority = URLSessionTask.defaultPriority
  150. }
  151. /// Reduce the download task priority if it is in progress.
  152. func reducePriorityOnDisappear() {
  153. guard let downloadTask = downloadTask, loading == true else { return }
  154. downloadTask.sessionTask?.task.priority = URLSessionTask.lowPriority
  155. }
  156. }
  157. }
  158. #endif