ImageBinder.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. import Combine
  27. import SwiftUI
  28. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  29. extension KFImage {
  30. public class ImageBinder: BindableObject {
  31. let url: URL
  32. public var didChange = PassthroughSubject<KFCrossPlatformImage?, Never>()
  33. var subject = PassthroughSubject<RetrieveImageResult, KingfisherError>()
  34. var downloadTask: DownloadTask?
  35. var image: Kingfisher.KFCrossPlatformImage? {
  36. didSet { didChange.send(image) }
  37. }
  38. init(url: URL) {
  39. self.url = url
  40. }
  41. func start() {
  42. let source = Source.network(url)
  43. downloadTask = KingfisherManager.shared
  44. .retrieveImage(with: source) { [weak self] result in
  45. guard let self = self else { return }
  46. self.downloadTask = nil
  47. switch result {
  48. case .success(let value):
  49. self.image = value.image
  50. self.subject.send(value)
  51. self.subject.send(completion: .finished)
  52. case .failure(let error):
  53. self.subject.send(completion: .failure(error))
  54. }
  55. }
  56. }
  57. public func cancel() {
  58. downloadTask?.cancel()
  59. }
  60. }
  61. }