UIButton+Kingfisher.swift 19 KB

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