UIButton+Kingfisher.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. //
  2. // UIButton+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/13.
  6. //
  7. // Copyright (c) 2019 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 !os(watchOS)
  27. #if canImport(UIKit)
  28. import UIKit
  29. @MainActor
  30. extension KingfisherWrapper where Base: UIButton {
  31. // MARK: Setting Image
  32. /// Sets an image to the button for a specified state with a source.
  33. ///
  34. /// - Parameters:
  35. /// - source: The `Source` object contains information about the image.
  36. /// - state: The button state to which the image should be set.
  37. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  38. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  39. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  40. /// `expectedContentLength`, this block will not be called.
  41. /// - completionHandler: Called when the image retrieved and set finished.
  42. /// - Returns: A task represents the image downloading.
  43. ///
  44. /// - Note:
  45. /// Internally, this method will use `KingfisherManager` to get the requested source, from either cache
  46. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  47. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  48. ///
  49. @discardableResult
  50. public func setImage(
  51. with source: Source?,
  52. for state: UIControl.State,
  53. placeholder: UIImage? = nil,
  54. options: KingfisherOptionsInfo? = nil,
  55. progressBlock: DownloadProgressBlock? = nil,
  56. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  57. {
  58. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  59. return setImage(
  60. with: source,
  61. for: state,
  62. placeholder: placeholder,
  63. parsedOptions: options,
  64. progressBlock: progressBlock,
  65. completionHandler: completionHandler
  66. )
  67. }
  68. /// Sets an image to the button for a specified state with a requested resource.
  69. ///
  70. /// - Parameters:
  71. /// - resource: The `Resource` object contains information about the resource.
  72. /// - state: The button state to which the image should be set.
  73. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  74. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  75. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  76. /// `expectedContentLength`, this block will not be called.
  77. /// - completionHandler: Called when the image retrieved and set finished.
  78. /// - Returns: A task represents the image downloading.
  79. ///
  80. /// - Note:
  81. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  82. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  83. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  84. ///
  85. @discardableResult
  86. public func setImage(
  87. with resource: Resource?,
  88. for state: UIControl.State,
  89. placeholder: UIImage? = nil,
  90. options: KingfisherOptionsInfo? = nil,
  91. progressBlock: DownloadProgressBlock? = nil,
  92. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  93. {
  94. return setImage(
  95. with: resource?.convertToSource(),
  96. for: state,
  97. placeholder: placeholder,
  98. options: options,
  99. progressBlock: progressBlock,
  100. completionHandler: completionHandler)
  101. }
  102. @discardableResult
  103. public func setImage(
  104. with source: Source?,
  105. for state: UIControl.State,
  106. placeholder: UIImage? = nil,
  107. parsedOptions: KingfisherParsedOptionsInfo,
  108. progressBlock: DownloadProgressBlock? = nil,
  109. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  110. {
  111. guard let source = source else {
  112. base.setImage(placeholder, for: state)
  113. setTaskIdentifier(nil, for: state)
  114. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  115. return nil
  116. }
  117. var options = parsedOptions
  118. if !options.keepCurrentImageWhileLoading {
  119. base.setImage(placeholder, for: state)
  120. }
  121. var mutatingSelf = self
  122. let issuedIdentifier = Source.Identifier.next()
  123. setTaskIdentifier(issuedIdentifier, for: state)
  124. if let block = progressBlock {
  125. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  126. }
  127. let task = KingfisherManager.shared.retrieveImage(
  128. with: source,
  129. options: options,
  130. downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
  131. progressiveImageSetter: { self.base.setImage($0, for: state) },
  132. referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier(for: state) },
  133. completionHandler: { result in
  134. CallbackQueue.mainCurrentOrAsync.execute {
  135. guard issuedIdentifier == self.taskIdentifier(for: state) else {
  136. let reason: KingfisherError.ImageSettingErrorReason
  137. do {
  138. let value = try result.get()
  139. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  140. } catch {
  141. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  142. }
  143. let error = KingfisherError.imageSettingError(reason: reason)
  144. completionHandler?(.failure(error))
  145. return
  146. }
  147. mutatingSelf.imageTask = nil
  148. mutatingSelf.setTaskIdentifier(nil, for: state)
  149. switch result {
  150. case .success(let value):
  151. self.base.setImage(value.image, for: state)
  152. completionHandler?(result)
  153. case .failure:
  154. if let image = options.onFailureImage {
  155. self.base.setImage(image, for: state)
  156. }
  157. completionHandler?(result)
  158. }
  159. }
  160. }
  161. )
  162. mutatingSelf.imageTask = task
  163. return task
  164. }
  165. // MARK: Cancelling Downloading Task
  166. /// Cancels the image download task of the button if it is running.
  167. /// Nothing will happen if the downloading has already finished.
  168. public func cancelImageDownloadTask() {
  169. imageTask?.cancel()
  170. }
  171. // MARK: Setting Background Image
  172. /// Sets a background image to the button for a specified state with a source.
  173. ///
  174. /// - Parameters:
  175. /// - source: The `Source` object contains information about the image.
  176. /// - state: The button state to which the image should be set.
  177. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  178. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  179. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  180. /// `expectedContentLength`, this block will not be called.
  181. /// - completionHandler: Called when the image retrieved and set finished.
  182. /// - Returns: A task represents the image downloading.
  183. ///
  184. /// - Note:
  185. /// Internally, this method will use `KingfisherManager` to get the requested source
  186. /// Since this method will perform UI changes, you must call it from the main thread.
  187. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  188. ///
  189. @discardableResult
  190. public func setBackgroundImage(
  191. with source: Source?,
  192. for state: UIControl.State,
  193. placeholder: UIImage? = nil,
  194. options: KingfisherOptionsInfo? = nil,
  195. progressBlock: DownloadProgressBlock? = nil,
  196. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  197. {
  198. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  199. return setBackgroundImage(
  200. with: source,
  201. for: state,
  202. placeholder: placeholder,
  203. parsedOptions: options,
  204. progressBlock: progressBlock,
  205. completionHandler: completionHandler
  206. )
  207. }
  208. /// Sets a background image to the button for a specified state with a requested resource.
  209. ///
  210. /// - Parameters:
  211. /// - resource: The `Resource` object contains information about the resource.
  212. /// - state: The button state to which the image should be set.
  213. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  214. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  215. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  216. /// `expectedContentLength`, this block will not be called.
  217. /// - completionHandler: Called when the image retrieved and set finished.
  218. /// - Returns: A task represents the image downloading.
  219. ///
  220. /// - Note:
  221. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  222. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  223. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  224. ///
  225. @discardableResult
  226. public func setBackgroundImage(
  227. with resource: Resource?,
  228. for state: UIControl.State,
  229. placeholder: UIImage? = nil,
  230. options: KingfisherOptionsInfo? = nil,
  231. progressBlock: DownloadProgressBlock? = nil,
  232. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  233. {
  234. return setBackgroundImage(
  235. with: resource?.convertToSource(),
  236. for: state,
  237. placeholder: placeholder,
  238. options: options,
  239. progressBlock: progressBlock,
  240. completionHandler: completionHandler)
  241. }
  242. func setBackgroundImage(
  243. with source: Source?,
  244. for state: UIControl.State,
  245. placeholder: UIImage? = nil,
  246. parsedOptions: KingfisherParsedOptionsInfo,
  247. progressBlock: DownloadProgressBlock? = nil,
  248. completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  249. {
  250. guard let source = source else {
  251. base.setBackgroundImage(placeholder, for: state)
  252. setBackgroundTaskIdentifier(nil, for: state)
  253. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  254. return nil
  255. }
  256. var options = parsedOptions
  257. if !options.keepCurrentImageWhileLoading {
  258. base.setBackgroundImage(placeholder, for: state)
  259. }
  260. var mutatingSelf = self
  261. let issuedIdentifier = Source.Identifier.next()
  262. setBackgroundTaskIdentifier(issuedIdentifier, for: state)
  263. if let block = progressBlock {
  264. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  265. }
  266. let task = KingfisherManager.shared.retrieveImage(
  267. with: source,
  268. options: options,
  269. downloadTaskUpdated: { mutatingSelf.backgroundImageTask = $0 },
  270. progressiveImageSetter: { self.base.setBackgroundImage($0, for: state) },
  271. referenceTaskIdentifierChecker: { issuedIdentifier == self.backgroundTaskIdentifier(for: state) },
  272. completionHandler: { result in
  273. CallbackQueue.mainCurrentOrAsync.execute {
  274. guard issuedIdentifier == self.backgroundTaskIdentifier(for: state) else {
  275. let reason: KingfisherError.ImageSettingErrorReason
  276. do {
  277. let value = try result.get()
  278. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  279. } catch {
  280. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  281. }
  282. let error = KingfisherError.imageSettingError(reason: reason)
  283. completionHandler?(.failure(error))
  284. return
  285. }
  286. mutatingSelf.backgroundImageTask = nil
  287. mutatingSelf.setBackgroundTaskIdentifier(nil, for: state)
  288. switch result {
  289. case .success(let value):
  290. self.base.setBackgroundImage(value.image, for: state)
  291. completionHandler?(result)
  292. case .failure:
  293. if let image = options.onFailureImage {
  294. self.base.setBackgroundImage(image, for: state)
  295. }
  296. completionHandler?(result)
  297. }
  298. }
  299. }
  300. )
  301. mutatingSelf.backgroundImageTask = task
  302. return task
  303. }
  304. // MARK: Cancelling Background Downloading Task
  305. /// Cancels the background image download task of the button if it is running.
  306. /// Nothing will happen if the downloading has already finished.
  307. public func cancelBackgroundImageDownloadTask() {
  308. backgroundImageTask?.cancel()
  309. }
  310. }
  311. // MARK: - Associated Object
  312. private var taskIdentifierKey: Void?
  313. private var imageTaskKey: Void?
  314. // MARK: Properties
  315. extension KingfisherWrapper where Base: UIButton {
  316. private typealias TaskIdentifier = Box<[UInt: Source.Identifier.Value]>
  317. public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? {
  318. return taskIdentifierInfo.value[state.rawValue]
  319. }
  320. private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) {
  321. taskIdentifierInfo.value[state.rawValue] = identifier
  322. }
  323. private var taskIdentifierInfo: TaskIdentifier {
  324. return getAssociatedObject(base, &taskIdentifierKey) ?? {
  325. setRetainedAssociatedObject(base, &taskIdentifierKey, $0)
  326. return $0
  327. } (TaskIdentifier([:]))
  328. }
  329. private var imageTask: DownloadTask? {
  330. get { return getAssociatedObject(base, &imageTaskKey) }
  331. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  332. }
  333. }
  334. private var backgroundTaskIdentifierKey: Void?
  335. private var backgroundImageTaskKey: Void?
  336. // MARK: Background Properties
  337. extension KingfisherWrapper where Base: UIButton {
  338. public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? {
  339. return backgroundTaskIdentifierInfo.value[state.rawValue]
  340. }
  341. private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) {
  342. backgroundTaskIdentifierInfo.value[state.rawValue] = identifier
  343. }
  344. private var backgroundTaskIdentifierInfo: TaskIdentifier {
  345. return getAssociatedObject(base, &backgroundTaskIdentifierKey) ?? {
  346. setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, $0)
  347. return $0
  348. } (TaskIdentifier([:]))
  349. }
  350. private var backgroundImageTask: DownloadTask? {
  351. get { return getAssociatedObject(base, &backgroundImageTaskKey) }
  352. mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) }
  353. }
  354. }
  355. #endif
  356. #endif