ImageBinder.swift 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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 progress: Progress = .init()
  47. func markLoading() {
  48. loading = true
  49. }
  50. func markLoaded(sendChangeEvent: Bool) {
  51. loaded = true
  52. if sendChangeEvent {
  53. objectWillChange.send()
  54. }
  55. }
  56. func start<HoldingView: KFImageHoldingView>(context: Context<HoldingView>) {
  57. guard let source = context.source else {
  58. CallbackQueueMain.currentOrAsync {
  59. context.onFailureDelegate.call(KingfisherError.imageSettingError(reason: .emptySource))
  60. if let image = context.options.onFailureImage {
  61. self.loadedImage = image
  62. }
  63. self.loading = false
  64. self.markLoaded(sendChangeEvent: false)
  65. }
  66. return
  67. }
  68. loading = true
  69. progress = .init()
  70. downloadTask = KingfisherManager.shared
  71. .retrieveImage(
  72. with: source,
  73. options: context.options,
  74. progressBlock: { size, total in
  75. self.updateProgress(downloaded: size, total: total)
  76. context.onProgressDelegate.call((size, total))
  77. },
  78. progressiveImageSetter: { image in
  79. CallbackQueueMain.currentOrAsync {
  80. self.markLoaded(sendChangeEvent: true)
  81. self.loadedImage = image
  82. }
  83. },
  84. completionHandler: { [weak self] result in
  85. guard let self else { return }
  86. CallbackQueueMain.currentOrAsync {
  87. self.downloadTask = nil
  88. self.loading = false
  89. }
  90. switch result {
  91. case .success(let value):
  92. CallbackQueueMain.currentOrAsync {
  93. if let fadeDuration = context.fadeTransitionDuration(cacheType: value.cacheType) {
  94. self.animating = true
  95. let animation = Animation.linear(duration: fadeDuration)
  96. withAnimation(animation) {
  97. // Trigger the view render to apply the animation.
  98. self.markLoaded(sendChangeEvent: true)
  99. }
  100. } else {
  101. self.markLoaded(sendChangeEvent: false)
  102. }
  103. self.loadedImage = value.image
  104. self.animating = false
  105. }
  106. CallbackQueueMain.async {
  107. context.onSuccessDelegate.call(value)
  108. }
  109. case .failure(let error):
  110. CallbackQueueMain.currentOrAsync {
  111. if let image = context.options.onFailureImage {
  112. self.loadedImage = image
  113. }
  114. self.markLoaded(sendChangeEvent: false)
  115. }
  116. CallbackQueueMain.async {
  117. context.onFailureDelegate.call(error)
  118. }
  119. }
  120. })
  121. }
  122. private func updateProgress(downloaded: Int64, total: Int64) {
  123. progress.totalUnitCount = total
  124. progress.completedUnitCount = downloaded
  125. objectWillChange.send()
  126. }
  127. /// Cancels the download task if it is in progress.
  128. func cancel() {
  129. downloadTask?.cancel()
  130. downloadTask = nil
  131. loading = false
  132. }
  133. /// Restores the download task priority to default if it is in progress.
  134. func restorePriorityOnAppear() {
  135. guard let downloadTask = downloadTask, loading == true else { return }
  136. downloadTask.sessionTask?.task.priority = URLSessionTask.defaultPriority
  137. }
  138. /// Reduce the download task priority if it is in progress.
  139. func reducePriorityOnDisappear() {
  140. guard let downloadTask = downloadTask, loading == true else { return }
  141. downloadTask.sessionTask?.task.priority = URLSessionTask.lowPriority
  142. }
  143. }
  144. }
  145. #endif