KF.swift 19 KB

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