ImageBinder.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. @Published var loaded = false
  41. @Published var loadedImage: KFCrossPlatformImage? = nil
  42. @Published var progress: Progress = .init()
  43. func start<HoldingView: KFImageHoldingView>(context: Context<HoldingView>) {
  44. guard let source = context.source else {
  45. CallbackQueue.mainCurrentOrAsync.execute {
  46. context.onFailureDelegate.call(KingfisherError.imageSettingError(reason: .emptySource))
  47. }
  48. return
  49. }
  50. loading = true
  51. progress = .init()
  52. downloadTask = KingfisherManager.shared
  53. .retrieveImage(
  54. with: source,
  55. options: context.options,
  56. progressBlock: { size, total in
  57. self.updateProgress(downloaded: size, total: total)
  58. context.onProgressDelegate.call((size, total))
  59. },
  60. completionHandler: { [weak self] result in
  61. guard let self = self else { return }
  62. CallbackQueue.mainCurrentOrAsync.execute {
  63. self.downloadTask = nil
  64. self.loading = false
  65. }
  66. switch result {
  67. case .success(let value):
  68. CallbackQueue.mainCurrentOrAsync.execute {
  69. self.loadedImage = value.image
  70. let animation = context.fadeTransitionDuration(cacheType: value.cacheType)
  71. .map { duration in Animation.linear(duration: duration) }
  72. withAnimation(animation) { self.loaded = true }
  73. }
  74. CallbackQueue.mainAsync.execute {
  75. context.onSuccessDelegate.call(value)
  76. }
  77. case .failure(let error):
  78. CallbackQueue.mainCurrentOrAsync.execute {
  79. if let image = context.options.onFailureImage {
  80. self.loadedImage = image
  81. }
  82. self.loaded = true
  83. }
  84. CallbackQueue.mainAsync.execute {
  85. context.onFailureDelegate.call(error)
  86. }
  87. }
  88. })
  89. }
  90. private func updateProgress(downloaded: Int64, total: Int64) {
  91. progress.totalUnitCount = total
  92. progress.completedUnitCount = downloaded
  93. objectWillChange.send()
  94. }
  95. /// Cancels the download task if it is in progress.
  96. func cancel() {
  97. downloadTask?.cancel()
  98. downloadTask = nil
  99. loading = false
  100. }
  101. }
  102. }
  103. #endif