ImageBinder.swift 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. public enum KFImageLoadingState {
  30. case notLoaded
  31. case loaded(RetrieveImageResult)
  32. case error(KingfisherError)
  33. }
  34. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  35. extension KFImage {
  36. /// Represents a binder for `KFImage`. It takes responsibility as an `ObjectBinding` and performs
  37. /// image downloading and progress reporting based on `KingfisherManager`.
  38. public class ImageBinder: ObservableObject {
  39. let source: Source?
  40. private var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions)
  41. var downloadTask: DownloadTask?
  42. var loadingOrSucceeded: Bool = false
  43. let onFailureDelegate = Delegate<KingfisherError, Void>()
  44. let onSuccessDelegate = Delegate<RetrieveImageResult, Void>()
  45. let onProgressDelegate = Delegate<(Int64, Int64), Void>()
  46. var isLoaded: Binding<Bool>
  47. var loadingState: Binding<KFImageLoadingState>?
  48. @Published var image: KFCrossPlatformImage?
  49. init(source: Source?, options: KingfisherOptionsInfo?, isLoaded: Binding<Bool>) {
  50. self.source = source
  51. // The refreshing of `KFImage` would happen much more frequently then an `UIImageView`, even as a
  52. // "side-effect". To prevent unintended flickering, add `.loadDiskFileSynchronously` as a default.
  53. self.options = KingfisherParsedOptionsInfo(
  54. KingfisherManager.shared.defaultOptions +
  55. (options ?? []) +
  56. [.loadDiskFileSynchronously]
  57. )
  58. self.isLoaded = isLoaded
  59. self.image = nil
  60. }
  61. init(source: Source?, loadingState: Binding<KFImageLoadingState>? = nil) {
  62. self.source = source
  63. self.options = KingfisherParsedOptionsInfo(
  64. KingfisherManager.shared.defaultOptions + [.loadDiskFileSynchronously]
  65. )
  66. self.isLoaded = .constant(false)
  67. self.loadingState = loadingState
  68. self.image = nil
  69. }
  70. func start() {
  71. guard !loadingOrSucceeded else { return }
  72. loadingOrSucceeded = true
  73. guard let source = source else {
  74. CallbackQueue.mainCurrentOrAsync.execute {
  75. self.onFailureDelegate.call(KingfisherError.imageSettingError(reason: .emptySource))
  76. }
  77. return
  78. }
  79. downloadTask = KingfisherManager.shared
  80. .retrieveImage(
  81. with: source,
  82. options: options,
  83. progressBlock: { size, total in
  84. self.onProgressDelegate.call((size, total))
  85. },
  86. completionHandler: { [weak self] result in
  87. guard let self = self else { return }
  88. self.downloadTask = nil
  89. switch result {
  90. case .success(let value):
  91. // The normalized version of image is used to solve #1395
  92. // It should be not necessary if SwiftUI.Image can handle resizing correctly when created
  93. // by `Image.init(uiImage:)`. (The orientation information should be already contained in
  94. // a `UIImage`)
  95. // https://github.com/onevcat/Kingfisher/issues/1395
  96. let image = value.image.kf.normalized
  97. CallbackQueue.mainCurrentOrAsync.execute {
  98. self.image = image
  99. }
  100. CallbackQueue.mainAsync.execute {
  101. self.isLoaded.wrappedValue = true
  102. self.onSuccessDelegate.call(value)
  103. }
  104. case .failure(let error):
  105. self.loadingOrSucceeded = false
  106. CallbackQueue.mainAsync.execute {
  107. self.onFailureDelegate.call(error)
  108. }
  109. }
  110. })
  111. }
  112. /// Cancels the download task if it is in progress.
  113. public func cancel() {
  114. downloadTask?.cancel()
  115. }
  116. func setOnFailure(perform action: ((KingfisherError) -> Void)?) {
  117. onFailureDelegate.delegate(on: self) { (self, error) in
  118. action?(error)
  119. }
  120. }
  121. func setOnSuccess(perform action: ((RetrieveImageResult) -> Void)?) {
  122. onSuccessDelegate.delegate(on: self) { (self, result) in
  123. action?(result)
  124. }
  125. }
  126. func setOnProgress(perform action: ((Int64, Int64) -> Void)?) {
  127. onProgressDelegate.delegate(on: self) { (self, result) in
  128. action?(result.0, result.1)
  129. }
  130. }
  131. }
  132. }
  133. #endif