KFImageOptions.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 the
  117. /// deprecated `onFailureImage` API 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 deprecated `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. /// Sets an image to display when the loading fails.
  144. ///
  145. /// - Deprecated: Use ``onFailureView(_:)`` instead, which lets you return any SwiftUI `View` and guarantees
  146. /// consistent behavior across SwiftUI platforms. The image-based fallback modifier is maintained purely for
  147. /// backward compatibility and will be removed in a future major release.
  148. @available(*, deprecated, message: "Use `onFailureView(_:)` to customize SwiftUI failure placeholders instead.")
  149. public func onFailureImage(_ image: KFCrossPlatformImage?) -> Self {
  150. options.onFailureImage = .some(image)
  151. return self
  152. }
  153. /// Enables canceling the download task associated with `self` when the view disappears.
  154. ///
  155. /// - Parameter flag: A boolean value indicating whether to cancel the task.
  156. /// - Returns: A Kingfisher-compatible image view that cancels the download task when it disappears.
  157. public func cancelOnDisappear(_ flag: Bool) -> Self {
  158. context.cancelOnDisappear = flag
  159. return self
  160. }
  161. /// Sets reduce priority of the download task to low, bound to `self` when the view disappearing.
  162. /// - Parameter flag: Whether reduce the priority task or not.
  163. /// - Returns: A `KFImage` view that reduces downloading task priority when disappears.
  164. public func reducePriorityOnDisappear(_ flag: Bool) -> Self {
  165. context.reducePriorityOnDisappear = flag
  166. return self
  167. }
  168. /// Sets a fade transition for the image task.
  169. ///
  170. /// - Parameter duration: The duration of the fade transition.
  171. /// - Returns: A Kingfisher-compatible image view with the applied changes.
  172. ///
  173. /// Kingfisher will use the fade transition to animate the image if it is downloaded from the web. The transition
  174. /// will not occur when the image is retrieved from either memory or disk cache by default. If you need the
  175. /// transition to occur even when the image is retrieved from the cache, also call
  176. /// ``KFOptionSetter/forceRefresh(_:)`` on the returned view.
  177. public func fade(duration: TimeInterval) -> Self {
  178. context.options.transition = .fade(duration)
  179. return self
  180. }
  181. /// Sets whether to start the image loading before the view actually appears.
  182. ///
  183. /// - Parameter flag: A boolean value indicating whether the image loading should happen before the view appears. The default is `true`.
  184. /// - Returns: A Kingfisher-compatible image view with the applied changes.
  185. ///
  186. /// By default, Kingfisher performs lazy loading for `KFImage`. The image loading won't start until the view's
  187. /// `onAppear` is called. However, sometimes you may want to trigger aggressive loading for the view. By enabling
  188. /// this, the `KFImage` will attempt to load the view when its `body` is evaluated if the image loading has not
  189. /// yet started or if a previous loading attempt failed.
  190. ///
  191. /// > Important: This was a temporary workaround for an issue that arose in iOS 16, where the SwiftUI view's
  192. /// > `onAppear` was not called when it was deeply embedded inside a `List` or `ForEach`. This is no longer necessary
  193. /// > if built with Xcode 14.3 and deployed to iOS 16.4 or later. So, it is not needed anymore.
  194. /// >
  195. /// > Enabling this may cause performance regression, especially if you have a lot of images to load in the view.
  196. /// > Use it at your own risk.
  197. /// >
  198. /// > Please refer to [#1988](https://github.com/onevcat/Kingfisher/issues/1988) for more information.
  199. public func startLoadingBeforeViewAppear(_ flag: Bool = true) -> Self {
  200. context.startLoadingBeforeViewAppear = flag
  201. return self
  202. }
  203. /// Sets a SwiftUI transition for the image loading.
  204. ///
  205. /// - Parameters:
  206. /// - transition: The SwiftUI transition to apply when the image appears.
  207. /// - animation: The animation to use with the transition. Defaults to `.default`.
  208. /// - Returns: A Kingfisher-compatible image view with the applied transition.
  209. ///
  210. /// This is the recommended way to apply transitions in SwiftUI applications. Unlike the UIKit-based
  211. /// ``KingfisherOptionsInfoItem/transition(_:)`` option, this method uses native SwiftUI transitions,
  212. /// providing better integration with the SwiftUI animation system and access to all SwiftUI transition types.
  213. ///
  214. /// Available transitions include `.slide`, `.scale`, `.opacity`, `.move`, `.offset`, and custom transitions.
  215. /// The transition will be applied when the image is loaded from the network, following the same
  216. /// rules as the fade transition regarding cache behavior and `forceTransition`.
  217. ///
  218. /// When both `loadTransition` and `fade` are set, `loadTransition` takes precedence.
  219. ///
  220. /// Example:
  221. /// ```swift
  222. /// KFImage(url)
  223. /// .loadTransition(.slide, animation: .easeInOut(duration: 0.5))
  224. /// ```
  225. ///
  226. /// - Note: For UIKit/AppKit applications, use ``KingfisherOptionsInfoItem/transition(_:)`` instead.
  227. public func loadTransition(_ transition: AnyTransition, animation: Animation? = .default) -> Self {
  228. context.swiftUITransition = transition
  229. context.swiftUIAnimation = animation
  230. return self
  231. }
  232. /// Sets a SwiftUI transition for the image loading (iOS 17.0+).
  233. ///
  234. /// - Parameters:
  235. /// - transition: The SwiftUI transition conforming to the Transition protocol.
  236. /// - animation: The animation to use with the transition. Defaults to `.default`.
  237. /// - Returns: A Kingfisher-compatible image view with the applied transition.
  238. ///
  239. /// This method provides access to newer SwiftUI transitions available in iOS 17.0+,
  240. /// such as `BlurReplaceTransition`, `PushTransition`, and other transitions conforming to the `Transition` protocol.
  241. /// This is the recommended approach for SwiftUI applications on iOS 17.0+.
  242. ///
  243. /// When both `loadTransition` and `fade` are set, `loadTransition` takes precedence.
  244. ///
  245. /// Example:
  246. /// ```swift
  247. /// KFImage(url)
  248. /// .loadTransition(.blurReplace(.downUp), animation: .bouncy)
  249. /// ```
  250. ///
  251. /// - Note: For UIKit/AppKit applications, use ``KingfisherOptionsInfoItem/transition(_:)`` instead.
  252. @available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)
  253. public func loadTransition<T: Transition>(_ transition: T, animation: Animation? = .default) -> Self {
  254. context.swiftUITransition = AnyTransition(transition)
  255. context.swiftUIAnimation = animation
  256. return self
  257. }
  258. }
  259. #endif