UIButton+Kingfisher.swift 17 KB

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