KF.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. //
  2. // KF.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2020/09/21.
  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(UIKit)
  27. import UIKit
  28. #endif
  29. #if canImport(CarPlay) && !targetEnvironment(macCatalyst)
  30. import CarPlay
  31. #endif
  32. #if canImport(AppKit) && !targetEnvironment(macCatalyst)
  33. import AppKit
  34. #endif
  35. #if canImport(WatchKit)
  36. import WatchKit
  37. #endif
  38. #if canImport(TVUIKit)
  39. import TVUIKit
  40. #endif
  41. /// A helper type to create image setting tasks in a builder pattern.
  42. ///
  43. /// Use methods in this type to create a ``KF/Builder`` instance and configure image tasks there.
  44. public enum KF {
  45. /// Creates a builder for a given ``Source``.
  46. /// - Parameter source: The ``Source`` object defines data information from network or a data provider.
  47. /// - Returns: A ``Builder`` for future configuration. After configuring the builder, call its
  48. /// `Builder/set(to:)` to start the image loading.
  49. public static func source(_ source: Source?) -> KF.Builder {
  50. Builder(source: source)
  51. }
  52. /// Creates a builder for a given ``Resource``.
  53. /// - Parameter resource: The ``Resource`` object defines data information like key or URL.
  54. /// - Returns: A ``Builder`` for future configuration. After configuring the builder, call its
  55. /// `Builder/set(to:)` to start the image loading.
  56. public static func resource(_ resource: Resource?) -> KF.Builder {
  57. source(resource?.convertToSource())
  58. }
  59. /// Creates a builder for a given `URL` and an optional cache key.
  60. /// - Parameters:
  61. /// - url: The URL where the image should be downloaded.
  62. /// - cacheKey: The key used to store the downloaded image in cache.
  63. /// If `nil`, the `absoluteString` of `url` is used as the cache key.
  64. /// - Returns: A ``Builder`` for future configuration. After configuring the builder, call its
  65. /// `Builder/set(to:)` to start the image loading.
  66. public static func url(_ url: URL?, cacheKey: String? = nil) -> KF.Builder {
  67. source(url?.convertToSource(overrideCacheKey: cacheKey))
  68. }
  69. /// Creates a builder for a given ``ImageDataProvider``.
  70. /// - Parameter provider: The ``ImageDataProvider`` object contains information about the data.
  71. /// - Returns: A ``Builder`` for future configuration. After configuring the builder, call its
  72. /// `Builder/set(to:)` to start the image loading.
  73. public static func dataProvider(_ provider: ImageDataProvider?) -> KF.Builder {
  74. source(provider?.convertToSource())
  75. }
  76. /// Creates a builder for some given raw data and a cache key.
  77. /// - Parameters:
  78. /// - data: The data object from which the image should be created.
  79. /// - cacheKey: The key used to store the downloaded image in cache.
  80. /// - Returns: A ``Builder`` for future configuration. After configuring the builder, call its
  81. /// `Builder/set(to:)` to start the image loading.
  82. public static func data(_ data: Data?, cacheKey: String) -> KF.Builder {
  83. if let data = data {
  84. return dataProvider(RawImageDataProvider(data: data, cacheKey: cacheKey))
  85. } else {
  86. return dataProvider(nil)
  87. }
  88. }
  89. }
  90. extension KF {
  91. /// A builder class to configure an image retrieving task and set it to a holder view or component.
  92. public class Builder {
  93. private let source: Source?
  94. #if os(watchOS)
  95. private var placeholder: KFCrossPlatformImage?
  96. #else
  97. private var placeholder: Placeholder?
  98. #endif
  99. public var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions)
  100. public let onFailureDelegate = Delegate<KingfisherError, Void>()
  101. public let onSuccessDelegate = Delegate<RetrieveImageResult, Void>()
  102. public let onProgressDelegate = Delegate<(Int64, Int64), Void>()
  103. init(source: Source?) {
  104. self.source = source
  105. }
  106. private var resultHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? {
  107. {
  108. switch $0 {
  109. case .success(let result):
  110. self.onSuccessDelegate(result)
  111. case .failure(let error):
  112. self.onFailureDelegate(error)
  113. }
  114. }
  115. }
  116. private var progressBlock: DownloadProgressBlock {
  117. { self.onProgressDelegate(($0, $1)) }
  118. }
  119. }
  120. }
  121. @MainActor
  122. extension KF.Builder {
  123. #if !os(watchOS)
  124. /// Builds the image task request and sets it to an image view.
  125. /// - Parameter imageView: The image view which loads the task and should be set with the image.
  126. /// - Returns: A task represents the image downloading, if initialized.
  127. /// This value is `nil` if the image is being loaded from cache.
  128. @discardableResult
  129. public func set(to imageView: KFCrossPlatformImageView) -> DownloadTask? {
  130. imageView.kf.setImage(
  131. with: source,
  132. placeholder: placeholder,
  133. parsedOptions: options,
  134. progressBlock: progressBlock,
  135. completionHandler: resultHandler
  136. )
  137. }
  138. /// Builds the image task request and sets it to an `NSTextAttachment` object.
  139. /// - Parameters:
  140. /// - attachment: The text attachment object which loads the task and should be set with the image.
  141. /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added.
  142. /// - Returns: A task represents the image downloading, if initialized.
  143. /// This value is `nil` if the image is being loaded from cache.
  144. @discardableResult
  145. public func set(to attachment: NSTextAttachment, attributedView: @autoclosure @escaping () -> KFCrossPlatformView) -> DownloadTask? {
  146. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  147. return attachment.kf.setImage(
  148. with: source,
  149. attributedView: attributedView,
  150. placeholder: placeholderImage,
  151. parsedOptions: options,
  152. progressBlock: progressBlock,
  153. completionHandler: resultHandler
  154. )
  155. }
  156. #if canImport(UIKit)
  157. /// Builds the image task request and sets it to a button.
  158. /// - Parameters:
  159. /// - button: The button which loads the task and should be set with the image.
  160. /// - state: The button state to which the image should be set.
  161. /// - Returns: A task represents the image downloading, if initialized.
  162. /// This value is `nil` if the image is being loaded from cache.
  163. @discardableResult
  164. public func set(to button: UIButton, for state: UIControl.State) -> DownloadTask? {
  165. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  166. return button.kf.setImage(
  167. with: source,
  168. for: state,
  169. placeholder: placeholderImage,
  170. parsedOptions: options,
  171. progressBlock: progressBlock,
  172. completionHandler: resultHandler
  173. )
  174. }
  175. /// Builds the image task request and sets it to the background image for a button.
  176. /// - Parameters:
  177. /// - button: The button which loads the task and should be set with the image.
  178. /// - state: The button state to which the image should be set.
  179. /// - Returns: A task represents the image downloading, if initialized.
  180. /// This value is `nil` if the image is being loaded from cache.
  181. @discardableResult
  182. public func setBackground(to button: UIButton, for state: UIControl.State) -> DownloadTask? {
  183. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  184. return button.kf.setBackgroundImage(
  185. with: source,
  186. for: state,
  187. placeholder: placeholderImage,
  188. parsedOptions: options,
  189. progressBlock: progressBlock,
  190. completionHandler: resultHandler
  191. )
  192. }
  193. #endif // end of canImport(UIKit)
  194. #if canImport(CarPlay) && !targetEnvironment(macCatalyst)
  195. /// Builds the image task request and sets it to the image for a list item.
  196. /// - Parameters:
  197. /// - listItem: The list item which loads the task and should be set with the image.
  198. /// - Returns: A task represents the image downloading, if initialized.
  199. /// This value is `nil` if the image is being loaded from cache.
  200. @available(iOS 14.0, *)
  201. @discardableResult
  202. public func set(to listItem: CPListItem) -> DownloadTask? {
  203. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  204. return listItem.kf.setImage(
  205. with: source,
  206. placeholder: placeholderImage,
  207. parsedOptions: options,
  208. progressBlock: progressBlock,
  209. completionHandler: resultHandler
  210. )
  211. }
  212. #endif
  213. #if canImport(AppKit) && !targetEnvironment(macCatalyst)
  214. /// Builds the image task request and sets it to a button.
  215. /// - Parameter button: The button which loads the task and should be set with the image.
  216. /// - Returns: A task represents the image downloading, if initialized.
  217. /// This value is `nil` if the image is being loaded from cache.
  218. @discardableResult
  219. public func set(to button: NSButton) -> DownloadTask? {
  220. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  221. return button.kf.setImage(
  222. with: source,
  223. placeholder: placeholderImage,
  224. parsedOptions: options,
  225. progressBlock: progressBlock,
  226. completionHandler: resultHandler
  227. )
  228. }
  229. /// Builds the image task request and sets it to the alternative image for a button.
  230. /// - Parameter button: The button which loads the task and should be set with the image.
  231. /// - Returns: A task represents the image downloading, if initialized.
  232. /// This value is `nil` if the image is being loaded from cache.
  233. @discardableResult
  234. public func setAlternative(to button: NSButton) -> DownloadTask? {
  235. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  236. return button.kf.setAlternateImage(
  237. with: source,
  238. placeholder: placeholderImage,
  239. parsedOptions: options,
  240. progressBlock: progressBlock,
  241. completionHandler: resultHandler
  242. )
  243. }
  244. #endif // end of canImport(AppKit)
  245. #endif // end of !os(watchOS)
  246. #if canImport(WatchKit)
  247. /// Builds the image task request and sets it to a `WKInterfaceImage` object.
  248. /// - Parameter interfaceImage: The watch interface image which loads the task and should be set with the image.
  249. /// - Returns: A task represents the image downloading, if initialized.
  250. /// This value is `nil` if the image is being loaded from cache.
  251. @discardableResult
  252. public func set(to interfaceImage: WKInterfaceImage) -> DownloadTask? {
  253. return interfaceImage.kf.setImage(
  254. with: source,
  255. placeholder: placeholder,
  256. parsedOptions: options,
  257. progressBlock: progressBlock,
  258. completionHandler: resultHandler
  259. )
  260. }
  261. #endif // end of canImport(WatchKit)
  262. #if canImport(TVUIKit)
  263. /// Builds the image task request and sets it to a TV monogram view.
  264. /// - Parameter monogramView: The monogram view which loads the task and should be set with the image.
  265. /// - Returns: A task represents the image downloading, if initialized.
  266. /// This value is `nil` if the image is being loaded from cache.
  267. @available(tvOS 12.0, *)
  268. @discardableResult
  269. public func set(to monogramView: TVMonogramView) -> DownloadTask? {
  270. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  271. return monogramView.kf.setImage(
  272. with: source,
  273. placeholder: placeholderImage,
  274. parsedOptions: options,
  275. progressBlock: progressBlock,
  276. completionHandler: resultHandler
  277. )
  278. }
  279. #endif // end of canImport(TVUIKit)
  280. }
  281. #if !os(watchOS)
  282. extension KF.Builder {
  283. #if os(iOS) || os(tvOS) || os(visionOS)
  284. /// Sets a placeholder which is used while retrieving the image.
  285. /// - Parameter placeholder: A placeholder to show while retrieving the image from its source.
  286. /// - Returns: A ``KF/Builder`` with changes applied.
  287. public func placeholder(_ placeholder: Placeholder?) -> Self {
  288. self.placeholder = placeholder
  289. return self
  290. }
  291. #endif
  292. /// Sets a placeholder image which is used while retrieving the image.
  293. /// - Parameter placeholder: An image to show while retrieving the image from its source.
  294. /// - Returns: A ``KF/Builder`` with changes applied.
  295. public func placeholder(_ image: KFCrossPlatformImage?) -> Self {
  296. self.placeholder = image
  297. return self
  298. }
  299. }
  300. #endif
  301. extension KF.Builder {
  302. #if os(iOS) || os(tvOS) || os(visionOS)
  303. /// Sets the transition for the image task.
  304. /// - Parameter transition: The desired transition effect when setting the image to image view.
  305. /// - Returns: A ``KF/Builder`` with changes applied.
  306. ///
  307. /// Kingfisher will use the `transition` parameter to animate the image in if it is downloaded from web.
  308. /// The transition will not happen when the image is retrieved from either memory or disk cache by default.
  309. /// If you need to do the transition even when the image being retrieved from cache, also call
  310. /// ``KFOptionSetter/forceRefresh(_:)`` on the returned ``KF/Builder``.
  311. public func transition(_ transition: ImageTransition) -> Self {
  312. options.transition = transition
  313. return self
  314. }
  315. /// Sets a fade transition for the image task.
  316. /// - Parameter duration: The duration of the fade transition.
  317. /// - Returns: A ``KF/Builder`` with changes applied.
  318. ///
  319. /// Kingfisher will use the `transition` parameter to animate the image in if it is downloaded from web.
  320. /// The transition will not happen when the image is retrieved from either memory or disk cache by default.
  321. /// If you need to do the transition even when the image being retrieved from cache, also call
  322. /// ``KFOptionSetter/forceRefresh(_:)`` on the returned ``KF/Builder``.
  323. public func fade(duration: TimeInterval) -> Self {
  324. options.transition = .fade(duration)
  325. return self
  326. }
  327. #endif
  328. /// Sets whether keeping the existing image of image view while setting another image to it.
  329. /// - Parameter enabled: Whether the existing image should be kept.
  330. /// - Returns: A ``KF/Builder`` with changes applied.
  331. ///
  332. /// By setting this option, the placeholder image parameter of image view extension method
  333. /// will be ignored and the current image will be kept while loading or downloading the new image.
  334. ///
  335. public func keepCurrentImageWhileLoading(_ enabled: Bool = true) -> Self {
  336. options.keepCurrentImageWhileLoading = enabled
  337. return self
  338. }
  339. /// Sets whether only the first frame from an animated image file should be loaded as a single image.
  340. /// - Parameter enabled: Whether the only the first frame should be loaded.
  341. /// - Returns: A ``KF/Builder`` with changes applied.
  342. ///
  343. /// Loading an animated images may take too much memory. It will be useful when you want to display a
  344. /// static preview of the first frame from an animated image.
  345. ///
  346. /// This option will be ignored if the target image is not animated image data.
  347. ///
  348. public func onlyLoadFirstFrame(_ enabled: Bool = true) -> Self {
  349. options.onlyLoadFirstFrame = enabled
  350. return self
  351. }
  352. /// Enables progressive image loading with a specified `ImageProgressive` setting to process the
  353. /// progressive JPEG data and display it in a progressive way.
  354. /// - Parameter progressive: The progressive settings which is used while loading.
  355. /// - Returns: A ``KF/Builder`` with changes applied.
  356. public func progressiveJPEG(_ progressive: ImageProgressive? = .init()) -> Self {
  357. options.progressiveJPEG = progressive
  358. return self
  359. }
  360. }
  361. // MARK: - Deprecated
  362. extension KF.Builder {
  363. /// Starts the loading process of `self` immediately.
  364. ///
  365. /// By default, a ``KFImage`` will not load its source until the `onAppear` is called. This is a lazily loading
  366. /// behavior and provides better performance. However, when you refresh the view, the lazy loading also causes a
  367. /// flickering since the loading does not happen immediately. Call this method if you want to start the load at once
  368. /// could help avoiding the flickering, with some performance trade-off.
  369. ///
  370. /// - Returns: The `Self` value with changes applied.
  371. @available(*, deprecated, message: "This is not necessary anymore since `@StateObject` is used. It does nothing now and please just remove it.")
  372. public func loadImmediately(_ start: Bool = true) -> Self {
  373. return self
  374. }
  375. }
  376. // MARK: - Redirect Handler
  377. extension KF {
  378. /// Represents the detail information when a task redirect happens. It is wrapping necessary information for a
  379. /// ``ImageDownloadRedirectHandler``. See that protocol for more information.
  380. public struct RedirectPayload {
  381. /// The related session data task when the redirect happens. It is
  382. /// the current ``SessionDataTask`` which triggers this redirect.
  383. public let task: SessionDataTask
  384. /// The response received during redirection.
  385. public let response: HTTPURLResponse
  386. /// The request for redirection which can be modified.
  387. public let newRequest: URLRequest
  388. /// A closure for being called with modified request.
  389. public let completionHandler: (URLRequest?) -> Void
  390. }
  391. }