You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

390 lines
17 KiB

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