UIButton+Kingfisher.swift 17 KB

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