ImageBinder.swift 6.5 KB

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