KF.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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:)-2sm8j`` 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:)-2sm8j`` 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:)-2sm8j`` 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:)-2sm8j`` 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:)-2sm8j`` 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. extension KF.Builder {
  122. #if !os(watchOS)
  123. /// Builds the image task request and sets it to an image view.
  124. /// - Parameter imageView: The image view which loads the task and should be set with the image.
  125. /// - Returns: A task represents the image downloading, if initialized.
  126. /// This value is `nil` if the image is being loaded from cache.
  127. @discardableResult
  128. public func set(to imageView: KFCrossPlatformImageView) -> DownloadTask? {
  129. imageView.kf.setImage(
  130. with: source,
  131. placeholder: placeholder,
  132. parsedOptions: options,
  133. progressBlock: progressBlock,
  134. completionHandler: resultHandler
  135. )
  136. }
  137. /// Builds the image task request and sets it to an `NSTextAttachment` object.
  138. /// - Parameters:
  139. /// - attachment: The text attachment object which loads the task and should be set with the image.
  140. /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added.
  141. /// - Returns: A task represents the image downloading, if initialized.
  142. /// This value is `nil` if the image is being loaded from cache.
  143. @discardableResult
  144. public func set(to attachment: NSTextAttachment, attributedView: @autoclosure @escaping () -> KFCrossPlatformView) -> DownloadTask? {
  145. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  146. return attachment.kf.setImage(
  147. with: source,
  148. attributedView: attributedView,
  149. placeholder: placeholderImage,
  150. parsedOptions: options,
  151. progressBlock: progressBlock,
  152. completionHandler: resultHandler
  153. )
  154. }
  155. #if canImport(UIKit)
  156. /// Builds the image task request and sets it to a button.
  157. /// - Parameters:
  158. /// - button: The button which loads the task and should be set with the image.
  159. /// - state: The button state to which the image should be set.
  160. /// - Returns: A task represents the image downloading, if initialized.
  161. /// This value is `nil` if the image is being loaded from cache.
  162. @discardableResult
  163. public func set(to button: UIButton, for state: UIControl.State) -> DownloadTask? {
  164. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  165. return button.kf.setImage(
  166. with: source,
  167. for: state,
  168. placeholder: placeholderImage,
  169. parsedOptions: options,
  170. progressBlock: progressBlock,
  171. completionHandler: resultHandler
  172. )
  173. }
  174. /// Builds the image task request and sets it to the background image for a button.
  175. /// - Parameters:
  176. /// - button: The button which loads the task and should be set with the image.
  177. /// - state: The button state to which the image should be set.
  178. /// - Returns: A task represents the image downloading, if initialized.
  179. /// This value is `nil` if the image is being loaded from cache.
  180. @discardableResult
  181. public func setBackground(to button: UIButton, for state: UIControl.State) -> DownloadTask? {
  182. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  183. return button.kf.setBackgroundImage(
  184. with: source,
  185. for: state,
  186. placeholder: placeholderImage,
  187. parsedOptions: options,
  188. progressBlock: progressBlock,
  189. completionHandler: resultHandler
  190. )
  191. }
  192. #endif // end of canImport(UIKit)
  193. #if canImport(CarPlay) && !targetEnvironment(macCatalyst)
  194. /// Builds the image task request and sets it to the image for a list item.
  195. /// - Parameters:
  196. /// - listItem: The list item which loads the task and should be set with the image.
  197. /// - Returns: A task represents the image downloading, if initialized.
  198. /// This value is `nil` if the image is being loaded from cache.
  199. @available(iOS 14.0, *)
  200. @discardableResult
  201. public func set(to listItem: CPListItem) -> DownloadTask? {
  202. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  203. return listItem.kf.setImage(
  204. with: source,
  205. placeholder: placeholderImage,
  206. parsedOptions: options,
  207. progressBlock: progressBlock,
  208. completionHandler: resultHandler
  209. )
  210. }
  211. #endif
  212. #if canImport(AppKit) && !targetEnvironment(macCatalyst)
  213. /// Builds the image task request and sets it to a button.
  214. /// - Parameter button: The button which loads the task and should be set with the image.
  215. /// - Returns: A task represents the image downloading, if initialized.
  216. /// This value is `nil` if the image is being loaded from cache.
  217. @discardableResult
  218. public func set(to button: NSButton) -> DownloadTask? {
  219. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  220. return button.kf.setImage(
  221. with: source,
  222. placeholder: placeholderImage,
  223. parsedOptions: options,
  224. progressBlock: progressBlock,
  225. completionHandler: resultHandler
  226. )
  227. }
  228. /// Builds the image task request and sets it to the alternative image for a button.
  229. /// - Parameter button: The button which loads the task and should be set with the image.
  230. /// - Returns: A task represents the image downloading, if initialized.
  231. /// This value is `nil` if the image is being loaded from cache.
  232. @discardableResult
  233. public func setAlternative(to button: NSButton) -> DownloadTask? {
  234. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  235. return button.kf.setAlternateImage(
  236. with: source,
  237. placeholder: placeholderImage,
  238. parsedOptions: options,
  239. progressBlock: progressBlock,
  240. completionHandler: resultHandler
  241. )
  242. }
  243. #endif // end of canImport(AppKit)
  244. #endif // end of !os(watchOS)
  245. #if canImport(WatchKit)
  246. /// Builds the image task request and sets it to a `WKInterfaceImage` object.
  247. /// - Parameter interfaceImage: The watch interface image which loads the task and should be set with the image.
  248. /// - Returns: A task represents the image downloading, if initialized.
  249. /// This value is `nil` if the image is being loaded from cache.
  250. @discardableResult
  251. public func set(to interfaceImage: WKInterfaceImage) -> DownloadTask? {
  252. return interfaceImage.kf.setImage(
  253. with: source,
  254. placeholder: placeholder,
  255. parsedOptions: options,
  256. progressBlock: progressBlock,
  257. completionHandler: resultHandler
  258. )
  259. }
  260. #endif // end of canImport(WatchKit)
  261. #if canImport(TVUIKit)
  262. /// Builds the image task request and sets it to a TV monogram view.
  263. /// - Parameter monogramView: The monogram view which loads the task and should be set with the image.
  264. /// - Returns: A task represents the image downloading, if initialized.
  265. /// This value is `nil` if the image is being loaded from cache.
  266. @available(tvOS 12.0, *)
  267. @discardableResult
  268. public func set(to monogramView: TVMonogramView) -> DownloadTask? {
  269. let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil
  270. return monogramView.kf.setImage(
  271. with: source,
  272. placeholder: placeholderImage,
  273. parsedOptions: options,
  274. progressBlock: progressBlock,
  275. completionHandler: resultHandler
  276. )
  277. }
  278. #endif // end of canImport(TVUIKit)
  279. }
  280. #if !os(watchOS)
  281. extension KF.Builder {
  282. #if os(iOS) || os(tvOS) || os(visionOS)
  283. /// Sets a placeholder which is used while retrieving the image.
  284. /// - Parameter placeholder: A placeholder to show while retrieving the image from its source.
  285. /// - Returns: A ``KF/Builder`` with changes applied.
  286. public func placeholder(_ placeholder: Placeholder?) -> Self {
  287. self.placeholder = placeholder
  288. return self
  289. }
  290. #endif
  291. /// Sets a placeholder image which is used while retrieving the image.
  292. /// - Parameter placeholder: An image to show while retrieving the image from its source.
  293. /// - Returns: A ``KF/Builder`` with changes applied.
  294. public func placeholder(_ image: KFCrossPlatformImage?) -> Self {
  295. self.placeholder = image
  296. return self
  297. }
  298. }
  299. #endif
  300. extension KF.Builder {
  301. #if os(iOS) || os(tvOS) || os(visionOS)
  302. /// Sets the transition for the image task.
  303. /// - Parameter transition: The desired transition effect when setting the image to image view.
  304. /// - Returns: A ``KF/Builder`` with changes applied.
  305. ///
  306. /// Kingfisher will use the `transition` parameter to animate the image in if it is downloaded from web.
  307. /// The transition will not happen when the image is retrieved from either memory or disk cache by default.
  308. /// If you need to do the transition even when the image being retrieved from cache, also call
  309. /// ``KFOptionSetter/forceRefresh(_:)`` on the returned ``KF/Builder``.
  310. public func transition(_ transition: ImageTransition) -> Self {
  311. options.transition = transition
  312. return self
  313. }
  314. /// Sets a fade transition for the image task.
  315. /// - Parameter duration: The duration of the fade transition.
  316. /// - Returns: A ``KF/Builder`` with changes applied.
  317. ///
  318. /// Kingfisher will use the `transition` parameter to animate the image in if it is downloaded from web.
  319. /// The transition will not happen when the image is retrieved from either memory or disk cache by default.
  320. /// If you need to do the transition even when the image being retrieved from cache, also call
  321. /// ``KFOptionSetter/forceRefresh(_:)`` on the returned ``KF/Builder``.
  322. public func fade(duration: TimeInterval) -> Self {
  323. options.transition = .fade(duration)
  324. return self
  325. }
  326. #endif
  327. /// Sets whether keeping the existing image of image view while setting another image to it.
  328. /// - Parameter enabled: Whether the existing image should be kept.
  329. /// - Returns: A ``KF/Builder`` with changes applied.
  330. ///
  331. /// By setting this option, the placeholder image parameter of image view extension method
  332. /// will be ignored and the current image will be kept while loading or downloading the new image.
  333. ///
  334. public func keepCurrentImageWhileLoading(_ enabled: Bool = true) -> Self {
  335. options.keepCurrentImageWhileLoading = enabled
  336. return self
  337. }
  338. /// Sets whether only the first frame from an animated image file should be loaded as a single image.
  339. /// - Parameter enabled: Whether the only the first frame should be loaded.
  340. /// - Returns: A ``KF/Builder`` with changes applied.
  341. ///
  342. /// Loading an animated images may take too much memory. It will be useful when you want to display a
  343. /// static preview of the first frame from an animated image.
  344. ///
  345. /// This option will be ignored if the target image is not animated image data.
  346. ///
  347. public func onlyLoadFirstFrame(_ enabled: Bool = true) -> Self {
  348. options.onlyLoadFirstFrame = enabled
  349. return self
  350. }
  351. /// Enables progressive image loading with a specified `ImageProgressive` setting to process the
  352. /// progressive JPEG data and display it in a progressive way.
  353. /// - Parameter progressive: The progressive settings which is used while loading.
  354. /// - Returns: A ``KF/Builder`` with changes applied.
  355. public func progressiveJPEG(_ progressive: ImageProgressive? = .init()) -> Self {
  356. options.progressiveJPEG = progressive
  357. return self
  358. }
  359. }
  360. // MARK: - Deprecated
  361. extension KF.Builder {
  362. /// Starts the loading process of `self` immediately.
  363. ///
  364. /// By default, a ``KFImage`` will not load its source until the `onAppear` is called. This is a lazily loading
  365. /// behavior and provides better performance. However, when you refresh the view, the lazy loading also causes a
  366. /// flickering since the loading does not happen immediately. Call this method if you want to start the load at once
  367. /// could help avoiding the flickering, with some performance trade-off.
  368. ///
  369. /// - Returns: The `Self` value with changes applied.
  370. @available(*, deprecated, message: "This is not necessary anymore since `@StateObject` is used. It does nothing now and please just remove it.")
  371. public func loadImmediately(_ start: Bool = true) -> Self {
  372. return self
  373. }
  374. }
  375. // MARK: - Redirect Handler
  376. extension KF {
  377. /// Represents the detail information when a task redirect happens. It is wrapping necessary information for a
  378. /// ``ImageDownloadRedirectHandler``. See that protocol for more information.
  379. public struct RedirectPayload {
  380. /// The related session data task when the redirect happens. It is
  381. /// the current ``SessionDataTask`` which triggers this redirect.
  382. public let task: SessionDataTask
  383. /// The response received during redirection.
  384. public let response: HTTPURLResponse
  385. /// The request for redirection which can be modified.
  386. public let newRequest: URLRequest
  387. /// A closure for being called with modified request.
  388. public let completionHandler: (URLRequest?) -> Void
  389. }
  390. }