UIButton+Kingfisher.swift 17 KB

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