UIButton+Kingfisher.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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: (@MainActor @Sendable (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: (@MainActor @Sendable (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: (@MainActor @Sendable (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: { task in
  131. Task { @MainActor in mutatingSelf.imageTask = task }
  132. },
  133. progressiveImageSetter: { self.base.setImage($0, for: state) },
  134. referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier(for: state) },
  135. completionHandler: { result in
  136. CallbackQueueMain.currentOrAsync {
  137. guard issuedIdentifier == self.taskIdentifier(for: state) else {
  138. let reason: KingfisherError.ImageSettingErrorReason
  139. do {
  140. let value = try result.get()
  141. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  142. } catch {
  143. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  144. }
  145. let error = KingfisherError.imageSettingError(reason: reason)
  146. completionHandler?(.failure(error))
  147. return
  148. }
  149. mutatingSelf.imageTask = nil
  150. mutatingSelf.setTaskIdentifier(nil, for: state)
  151. switch result {
  152. case .success(let value):
  153. self.base.setImage(value.image, for: state)
  154. completionHandler?(result)
  155. case .failure:
  156. if let image = options.onFailureImage {
  157. self.base.setImage(image, for: state)
  158. }
  159. completionHandler?(result)
  160. }
  161. }
  162. }
  163. )
  164. mutatingSelf.imageTask = task
  165. return task
  166. }
  167. // MARK: Cancelling Downloading Task
  168. /// Cancels the image download task of the button if it is running.
  169. /// Nothing will happen if the downloading has already finished.
  170. public func cancelImageDownloadTask() {
  171. imageTask?.cancel()
  172. }
  173. // MARK: Setting Background Image
  174. /// Sets a background image to the button for a specified state with a source.
  175. ///
  176. /// - Parameters:
  177. /// - source: The `Source` object contains information about the image.
  178. /// - state: The button state to which the image should be set.
  179. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  180. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  181. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  182. /// `expectedContentLength`, this block will not be called.
  183. /// - completionHandler: Called when the image retrieved and set finished.
  184. /// - Returns: A task represents the image downloading.
  185. ///
  186. /// - Note:
  187. /// Internally, this method will use `KingfisherManager` to get the requested source
  188. /// Since this method will perform UI changes, you must call it from the main thread.
  189. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  190. ///
  191. @discardableResult
  192. public func setBackgroundImage(
  193. with source: Source?,
  194. for state: UIControl.State,
  195. placeholder: UIImage? = nil,
  196. options: KingfisherOptionsInfo? = nil,
  197. progressBlock: DownloadProgressBlock? = nil,
  198. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  199. {
  200. let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty))
  201. return setBackgroundImage(
  202. with: source,
  203. for: state,
  204. placeholder: placeholder,
  205. parsedOptions: options,
  206. progressBlock: progressBlock,
  207. completionHandler: completionHandler
  208. )
  209. }
  210. /// Sets a background image to the button for a specified state with a requested resource.
  211. ///
  212. /// - Parameters:
  213. /// - resource: The `Resource` object contains information about the resource.
  214. /// - state: The button state to which the image should be set.
  215. /// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
  216. /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
  217. /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
  218. /// `expectedContentLength`, this block will not be called.
  219. /// - completionHandler: Called when the image retrieved and set finished.
  220. /// - Returns: A task represents the image downloading.
  221. ///
  222. /// - Note:
  223. /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
  224. /// or network. Since this method will perform UI changes, you must call it from the main thread.
  225. /// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
  226. ///
  227. @discardableResult
  228. public func setBackgroundImage(
  229. with resource: Resource?,
  230. for state: UIControl.State,
  231. placeholder: UIImage? = nil,
  232. options: KingfisherOptionsInfo? = nil,
  233. progressBlock: DownloadProgressBlock? = nil,
  234. completionHandler: (@Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  235. {
  236. return setBackgroundImage(
  237. with: resource?.convertToSource(),
  238. for: state,
  239. placeholder: placeholder,
  240. options: options,
  241. progressBlock: progressBlock,
  242. completionHandler: completionHandler)
  243. }
  244. func setBackgroundImage(
  245. with source: Source?,
  246. for state: UIControl.State,
  247. placeholder: UIImage? = nil,
  248. parsedOptions: KingfisherParsedOptionsInfo,
  249. progressBlock: DownloadProgressBlock? = nil,
  250. completionHandler: (@MainActor @Sendable (Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  251. {
  252. guard let source = source else {
  253. base.setBackgroundImage(placeholder, for: state)
  254. setBackgroundTaskIdentifier(nil, for: state)
  255. completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
  256. return nil
  257. }
  258. var options = parsedOptions
  259. if !options.keepCurrentImageWhileLoading {
  260. base.setBackgroundImage(placeholder, for: state)
  261. }
  262. var mutatingSelf = self
  263. let issuedIdentifier = Source.Identifier.next()
  264. setBackgroundTaskIdentifier(issuedIdentifier, for: state)
  265. if let block = progressBlock {
  266. options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
  267. }
  268. let task = KingfisherManager.shared.retrieveImage(
  269. with: source,
  270. options: options,
  271. downloadTaskUpdated: { task in
  272. Task { @MainActor in
  273. mutatingSelf.backgroundImageTask = task
  274. }
  275. },
  276. progressiveImageSetter: { self.base.setBackgroundImage($0, for: state) },
  277. referenceTaskIdentifierChecker: { issuedIdentifier == self.backgroundTaskIdentifier(for: state) },
  278. completionHandler: { result in
  279. CallbackQueueMain.currentOrAsync {
  280. guard issuedIdentifier == self.backgroundTaskIdentifier(for: state) else {
  281. let reason: KingfisherError.ImageSettingErrorReason
  282. do {
  283. let value = try result.get()
  284. reason = .notCurrentSourceTask(result: value, error: nil, source: source)
  285. } catch {
  286. reason = .notCurrentSourceTask(result: nil, error: error, source: source)
  287. }
  288. let error = KingfisherError.imageSettingError(reason: reason)
  289. completionHandler?(.failure(error))
  290. return
  291. }
  292. mutatingSelf.backgroundImageTask = nil
  293. mutatingSelf.setBackgroundTaskIdentifier(nil, for: state)
  294. switch result {
  295. case .success(let value):
  296. self.base.setBackgroundImage(value.image, for: state)
  297. completionHandler?(result)
  298. case .failure:
  299. if let image = options.onFailureImage {
  300. self.base.setBackgroundImage(image, for: state)
  301. }
  302. completionHandler?(result)
  303. }
  304. }
  305. }
  306. )
  307. mutatingSelf.backgroundImageTask = task
  308. return task
  309. }
  310. // MARK: Cancelling Background Downloading Task
  311. /// Cancels the background image download task of the button if it is running.
  312. /// Nothing will happen if the downloading has already finished.
  313. public func cancelBackgroundImageDownloadTask() {
  314. backgroundImageTask?.cancel()
  315. }
  316. }
  317. // MARK: - Associated Object
  318. @MainActor private var taskIdentifierKey: Void?
  319. @MainActor private var imageTaskKey: Void?
  320. // MARK: Properties
  321. @MainActor
  322. extension KingfisherWrapper where Base: UIButton {
  323. private typealias TaskIdentifier = Box<[UInt: Source.Identifier.Value]>
  324. public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? {
  325. return taskIdentifierInfo.value[state.rawValue]
  326. }
  327. private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) {
  328. taskIdentifierInfo.value[state.rawValue] = identifier
  329. }
  330. private var taskIdentifierInfo: TaskIdentifier {
  331. return getAssociatedObject(base, &taskIdentifierKey) ?? {
  332. setRetainedAssociatedObject(base, &taskIdentifierKey, $0)
  333. return $0
  334. } (TaskIdentifier([:]))
  335. }
  336. private var imageTask: DownloadTask? {
  337. get { return getAssociatedObject(base, &imageTaskKey) }
  338. set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
  339. }
  340. }
  341. @MainActor private var backgroundTaskIdentifierKey: Void?
  342. @MainActor private var backgroundImageTaskKey: Void?
  343. // MARK: Background Properties
  344. @MainActor
  345. extension KingfisherWrapper where Base: UIButton {
  346. public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? {
  347. return backgroundTaskIdentifierInfo.value[state.rawValue]
  348. }
  349. private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) {
  350. backgroundTaskIdentifierInfo.value[state.rawValue] = identifier
  351. }
  352. private var backgroundTaskIdentifierInfo: TaskIdentifier {
  353. return getAssociatedObject(base, &backgroundTaskIdentifierKey) ?? {
  354. setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, $0)
  355. return $0
  356. } (TaskIdentifier([:]))
  357. }
  358. private var backgroundImageTask: DownloadTask? {
  359. get { return getAssociatedObject(base, &backgroundImageTaskKey) }
  360. mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) }
  361. }
  362. }
  363. #endif
  364. #endif