ImageBinder.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 {
  34. let source: Source?
  35. var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions)
  36. var downloadTask: DownloadTask?
  37. var loadingOrSucceeded: Bool = false
  38. let onFailureDelegate = Delegate<KingfisherError, Void>()
  39. let onSuccessDelegate = Delegate<RetrieveImageResult, Void>()
  40. let onProgressDelegate = Delegate<(Int64, Int64), Void>()
  41. var isLoaded: Binding<Bool>
  42. @available(*, deprecated, message: "The `options` version is deprecated And will be removed soon.")
  43. init(source: Source?, options: KingfisherOptionsInfo? = nil, isLoaded: Binding<Bool>) {
  44. self.source = source
  45. // The refreshing of `KFImage` would happen much more frequently then an `UIImageView`, even as a
  46. // "side-effect". To prevent unintended flickering, add `.loadDiskFileSynchronously` as a default.
  47. self.options = KingfisherParsedOptionsInfo(
  48. KingfisherManager.shared.defaultOptions +
  49. (options ?? []) +
  50. [.loadDiskFileSynchronously]
  51. )
  52. self.isLoaded = isLoaded
  53. }
  54. init(source: Source?, isLoaded: Binding<Bool>) {
  55. self.source = source
  56. // The refreshing of `KFImage` would happen much more frequently then an `UIImageView`, even as a
  57. // "side-effect". To prevent unintended flickering, add `.loadDiskFileSynchronously` as a default.
  58. self.options = KingfisherParsedOptionsInfo(
  59. KingfisherManager.shared.defaultOptions +
  60. [.loadDiskFileSynchronously]
  61. )
  62. self.isLoaded = isLoaded
  63. }
  64. func start(_ done: @escaping (Result<RetrieveImageResult, KingfisherError>) -> Void) {
  65. guard !loadingOrSucceeded else { return }
  66. loadingOrSucceeded = true
  67. guard let source = source else {
  68. CallbackQueue.mainCurrentOrAsync.execute {
  69. self.onFailureDelegate.call(KingfisherError.imageSettingError(reason: .emptySource))
  70. }
  71. return
  72. }
  73. downloadTask = KingfisherManager.shared
  74. .retrieveImage(
  75. with: source,
  76. options: options,
  77. progressBlock: { size, total in
  78. self.onProgressDelegate.call((size, total))
  79. },
  80. completionHandler: { [weak self] result in
  81. guard let self = self else { return }
  82. self.downloadTask = nil
  83. switch result {
  84. case .success(let value):
  85. // The normalized version of image is used to solve #1395
  86. // It should be not necessary if SwiftUI.Image can handle resizing correctly when created
  87. // by `Image.init(uiImage:)`. (The orientation information should be already contained in
  88. // a `UIImage`)
  89. // https://github.com/onevcat/Kingfisher/issues/1395
  90. let image = value.image.kf.normalized
  91. let r = RetrieveImageResult(
  92. image: image, cacheType: value.cacheType, source: value.source, originalSource: value.originalSource
  93. )
  94. CallbackQueue.mainCurrentOrAsync.execute {
  95. done(.success(r))
  96. }
  97. CallbackQueue.mainAsync.execute {
  98. self.isLoaded.wrappedValue = true
  99. self.onSuccessDelegate.call(value)
  100. }
  101. case .failure(let error):
  102. self.loadingOrSucceeded = false
  103. CallbackQueue.mainCurrentOrAsync.execute {
  104. done(.failure(error))
  105. }
  106. CallbackQueue.mainAsync.execute {
  107. self.onFailureDelegate.call(error)
  108. }
  109. }
  110. })
  111. }
  112. /// Cancels the download task if it is in progress.
  113. func cancel() {
  114. downloadTask?.cancel()
  115. }
  116. }
  117. }
  118. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  119. extension KFImage.ImageBinder: Hashable {
  120. static func == (lhs: KFImage.ImageBinder, rhs: KFImage.ImageBinder) -> Bool {
  121. return lhs === rhs
  122. }
  123. func hash(into hasher: inout Hasher) {
  124. hasher.combine(source)
  125. hasher.combine(options.processor.identifier)
  126. }
  127. }
  128. #endif