UIButton+Kingfisher.swift 17 KB

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