KF.swift 17 KB

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