ImageBinder.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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)
  27. import SwiftUI
  28. @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
  29. extension KFImage {
  30. /// Represents a binder for `KFImage`. It takes responsibility as an `ObjectBinding` and performs
  31. /// image downloading and progress reporting based on `KingfisherManager`.
  32. class ImageBinder: ObservableObject {
  33. let source: Source?
  34. var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions)
  35. var downloadTask: DownloadTask?
  36. var loadingOrSucceeded: Bool {
  37. return downloadTask != nil || loadedImage != nil
  38. }
  39. let onFailureDelegate = Delegate<KingfisherError, Void>()
  40. let onSuccessDelegate = Delegate<RetrieveImageResult, Void>()
  41. let onProgressDelegate = Delegate<(Int64, Int64), Void>()
  42. var isLoaded: Binding<Bool>
  43. @Published var loaded = false
  44. @Published var loadedImage: KFCrossPlatformImage? = nil
  45. @available(*, deprecated, message: "The `options` version is deprecated And will be removed soon.")
  46. init(source: Source?, options: KingfisherOptionsInfo? = nil, isLoaded: Binding<Bool>) {
  47. self.source = source
  48. // The refreshing of `KFImage` would happen much more frequently then an `UIImageView`, even as a
  49. // "side-effect". To prevent unintended flickering, add `.loadDiskFileSynchronously` as a default.
  50. self.options = KingfisherParsedOptionsInfo(
  51. KingfisherManager.shared.defaultOptions +
  52. (options ?? []) +
  53. [.loadDiskFileSynchronously]
  54. )
  55. self.isLoaded = isLoaded
  56. }
  57. init(source: Source?, isLoaded: Binding<Bool>) {
  58. self.source = source
  59. // The refreshing of `KFImage` would happen much more frequently then an `UIImageView`, even as a
  60. // "side-effect". To prevent unintended flickering, add `.loadDiskFileSynchronously` as a default.
  61. self.options = KingfisherParsedOptionsInfo(
  62. KingfisherManager.shared.defaultOptions +
  63. [.loadDiskFileSynchronously]
  64. )
  65. self.isLoaded = isLoaded
  66. }
  67. func start() {
  68. guard !loadingOrSucceeded else { return }
  69. guard let source = source else {
  70. CallbackQueue.mainCurrentOrAsync.execute {
  71. self.onFailureDelegate.call(KingfisherError.imageSettingError(reason: .emptySource))
  72. }
  73. return
  74. }
  75. downloadTask = KingfisherManager.shared
  76. .retrieveImage(
  77. with: source,
  78. options: options,
  79. progressBlock: { size, total in
  80. self.onProgressDelegate.call((size, total))
  81. },
  82. completionHandler: { [weak self] result in
  83. guard let self = self else { return }
  84. self.downloadTask = nil
  85. switch result {
  86. case .success(let value):
  87. CallbackQueue.mainCurrentOrAsync.execute {
  88. self.loadedImage = value.image
  89. self.isLoaded.wrappedValue = true
  90. let animation = self.fadeTransitionDuration(cacheType: value.cacheType)
  91. .map { duration in Animation.linear(duration: duration) }
  92. withAnimation(animation) { self.loaded = true }
  93. }
  94. CallbackQueue.mainAsync.execute {
  95. self.onSuccessDelegate.call(value)
  96. }
  97. case .failure(let error):
  98. CallbackQueue.mainAsync.execute {
  99. self.onFailureDelegate.call(error)
  100. }
  101. }
  102. })
  103. }
  104. /// Cancels the download task if it is in progress.
  105. func cancel() {
  106. downloadTask?.cancel()
  107. downloadTask = nil
  108. }
  109. private func shouldApplyFade(cacheType: CacheType) -> Bool {
  110. options.forceTransition || cacheType == .none
  111. }
  112. private func fadeTransitionDuration(cacheType: CacheType) -> TimeInterval? {
  113. shouldApplyFade(cacheType: cacheType)
  114. ? options.transition.fadeDuration
  115. : nil
  116. }
  117. }
  118. }
  119. @available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
  120. extension KFImage.ImageBinder: Hashable {
  121. static func == (lhs: KFImage.ImageBinder, rhs: KFImage.ImageBinder) -> Bool {
  122. lhs.source == rhs.source && lhs.options.processor.identifier == rhs.options.processor.identifier
  123. }
  124. func hash(into hasher: inout Hasher) {
  125. hasher.combine(source)
  126. hasher.combine(options.processor.identifier)
  127. }
  128. }
  129. extension ImageTransition {
  130. // Only for fade effect in SwiftUI.
  131. fileprivate var fadeDuration: TimeInterval? {
  132. switch self {
  133. case .fade(let duration):
  134. return duration
  135. default:
  136. return nil
  137. }
  138. }
  139. }
  140. #endif