KFImageOptions.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. //
  2. // KFImageOptions.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2020/12/20.
  6. //
  7. // Copyright (c) 2020 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 SwiftUI
  28. import Combine
  29. // MARK: - KFImage creating.
  30. @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
  31. extension KFImageProtocol {
  32. /// Creates a Kingfisher-compatible image view with a given ``Source``.
  33. ///
  34. /// - Parameters:
  35. /// - source: The ``Source`` object that defines data information from the network or a data provider.
  36. /// - Returns: A Kingfisher-compatible image view for future configuration or embedding into another `SwiftUI.View`.
  37. public static func source(
  38. _ source: Source?
  39. ) -> Self
  40. {
  41. Self.init(source: source)
  42. }
  43. /// Creates a Kingfisher-compatible image view with a given ``Resource``.
  44. ///
  45. /// - Parameters:
  46. /// - resource: The ``Resource`` object that defines data information such as a key or URL.
  47. /// - Returns: A Kingfisher-compatible image view for future configuration or embedding into another `SwiftUI.View`.
  48. public static func resource(
  49. _ resource: (any Resource)?
  50. ) -> Self
  51. {
  52. source(resource?.convertToSource())
  53. }
  54. /// Creates a Kingfisher-compatible image view with a given `URL`.
  55. ///
  56. /// - Parameters:
  57. /// - url: The `URL` from which the image should be downloaded.
  58. /// - cacheKey: The key used to store the downloaded image in the cache. If `nil`, the `absoluteString` of `url`
  59. /// is used as the cache key.
  60. /// - Returns: A Kingfisher-compatible image view for future configuration or embedding into another `SwiftUI.View`.
  61. public static func url(
  62. _ url: URL?, cacheKey: String? = nil
  63. ) -> Self
  64. {
  65. source(url?.convertToSource(overrideCacheKey: cacheKey))
  66. }
  67. /// Creates a Kingfisher-compatible image view with a given ``ImageDataProvider``.
  68. ///
  69. /// - Parameters:
  70. /// - provider: The ``ImageDataProvider`` object that contains information about the data.
  71. /// - Returns: A Kingfisher-compatible image view for future configuration or embedding into another `SwiftUI.View`.
  72. public static func dataProvider(
  73. _ provider: (any ImageDataProvider)?
  74. ) -> Self
  75. {
  76. source(provider?.convertToSource())
  77. }
  78. /// Creates a builder for the provided raw data and a cache key.
  79. ///
  80. /// - Parameters:
  81. /// - data: The data object from which the image should be created.
  82. /// - cacheKey: The key used to store the downloaded image in the cache.
  83. /// - Returns: A Kingfisher-compatible image view for future configuration or embedding into another `SwiftUI.View`.
  84. public static func data(
  85. _ data: Data?, cacheKey: String
  86. ) -> Self
  87. {
  88. if let data = data {
  89. return dataProvider(RawImageDataProvider(data: data, cacheKey: cacheKey))
  90. } else {
  91. return dataProvider(nil)
  92. }
  93. }
  94. }
  95. @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
  96. extension KFImageProtocol {
  97. /// Sets a placeholder `View` that is displayed during the image loading, with a progress parameter as input.
  98. ///
  99. /// - Parameter content: A view that represents the placeholder.
  100. /// - Returns: A Kingfisher-compatible image view that includes the provided `content` as its placeholder.
  101. public func placeholder<P: View>(@ViewBuilder _ content: @escaping (Progress) -> P) -> Self {
  102. context.placeholder = { progress in
  103. return AnyView(content(progress))
  104. }
  105. return self
  106. }
  107. /// Sets a placeholder `View` that is displayed during the image loading.
  108. ///
  109. /// - Parameter content: A view that represents the placeholder.
  110. /// - Returns: A Kingfisher-compatible image view that includes the provided `content` as its placeholder.
  111. public func placeholder<P: View>(@ViewBuilder _ content: @escaping () -> P) -> Self {
  112. placeholder { _ in content() }
  113. }
  114. /// Sets a failure `View` that is displayed when the image fails to load.
  115. ///
  116. /// Use this modifier to provide a custom view when image loading fails. This offers more flexibility than
  117. /// `onFailureImage` by allowing any SwiftUI view as the failure placeholder.
  118. ///
  119. /// Example:
  120. /// ```swift
  121. /// KFImage(url)
  122. /// .onFailureView {
  123. /// VStack {
  124. /// Image(systemName: "exclamationmark.triangle")
  125. /// .foregroundColor(.red)
  126. /// Text("Failed to load image")
  127. /// .font(.caption)
  128. /// Button("Retry") {
  129. /// // Retry logic
  130. /// }
  131. /// }
  132. /// }
  133. /// ```
  134. ///
  135. /// - Note: If both `onFailureImage` and `onFailureView` are set, `onFailureView` takes precedence.
  136. ///
  137. /// - Parameter content: A view builder that creates the failure view.
  138. /// - Returns: A Kingfisher-compatible image view that displays the provided `content` when image loading fails.
  139. public func onFailureView<F: View>(@ViewBuilder _ content: @escaping () -> F) -> Self {
  140. context.failureView = { AnyView(content()) }
  141. return self
  142. }
  143. /// Enables canceling the download task associated with `self` when the view disappears.
  144. ///
  145. /// - Parameter flag: A boolean value indicating whether to cancel the task.
  146. /// - Returns: A Kingfisher-compatible image view that cancels the download task when it disappears.
  147. public func cancelOnDisappear(_ flag: Bool) -> Self {
  148. context.cancelOnDisappear = flag
  149. return self
  150. }
  151. /// Sets reduce priority of the download task to low, bound to `self` when the view disappearing.
  152. /// - Parameter flag: Whether reduce the priority task or not.
  153. /// - Returns: A `KFImage` view that reduces downloading task priority when disappears.
  154. public func reducePriorityOnDisappear(_ flag: Bool) -> Self {
  155. context.reducePriorityOnDisappear = flag
  156. return self
  157. }
  158. /// Sets a fade transition for the image task.
  159. ///
  160. /// - Parameter duration: The duration of the fade transition.
  161. /// - Returns: A Kingfisher-compatible image view with the applied changes.
  162. ///
  163. /// Kingfisher will use the fade transition to animate the image if it is downloaded from the web. The transition
  164. /// will not occur when the image is retrieved from either memory or disk cache by default. If you need the
  165. /// transition to occur even when the image is retrieved from the cache, also call
  166. /// ``KFOptionSetter/forceRefresh(_:)`` on the returned view.
  167. public func fade(duration: TimeInterval) -> Self {
  168. context.options.transition = .fade(duration)
  169. return self
  170. }
  171. /// Sets whether to start the image loading before the view actually appears.
  172. ///
  173. /// - Parameter flag: A boolean value indicating whether the image loading should happen before the view appears. The default is `true`.
  174. /// - Returns: A Kingfisher-compatible image view with the applied changes.
  175. ///
  176. /// By default, Kingfisher performs lazy loading for `KFImage`. The image loading won't start until the view's
  177. /// `onAppear` is called. However, sometimes you may want to trigger aggressive loading for the view. By enabling
  178. /// this, the `KFImage` will attempt to load the view when its `body` is evaluated if the image loading has not
  179. /// yet started or if a previous loading attempt failed.
  180. ///
  181. /// > Important: This was a temporary workaround for an issue that arose in iOS 16, where the SwiftUI view's
  182. /// > `onAppear` was not called when it was deeply embedded inside a `List` or `ForEach`. This is no longer necessary
  183. /// > if built with Xcode 14.3 and deployed to iOS 16.4 or later. So, it is not needed anymore.
  184. /// >
  185. /// > Enabling this may cause performance regression, especially if you have a lot of images to load in the view.
  186. /// > Use it at your own risk.
  187. /// >
  188. /// > Please refer to [#1988](https://github.com/onevcat/Kingfisher/issues/1988) for more information.
  189. public func startLoadingBeforeViewAppear(_ flag: Bool = true) -> Self {
  190. context.startLoadingBeforeViewAppear = flag
  191. return self
  192. }
  193. }
  194. #endif