UIButton+Kingfisher.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. //
  2. // UIButton+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/13.
  6. //
  7. // Copyright (c) 2018 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. // MARK: - Set Images
  28. /**
  29. * Set image to use in button from web for a specified state.
  30. */
  31. extension Kingfisher where Base: UIButton {
  32. /**
  33. Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and
  34. completion handler.
  35. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
  36. - parameter state: The state that uses the specified image.
  37. - parameter placeholder: A placeholder image when retrieving the image at URL.
  38. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  39. - parameter progressBlock: Called when the image downloading progress gets updated.
  40. - parameter completionHandler: Called when the image retrieved and set.
  41. - returns: A task represents the retrieving process.
  42. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
  43. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
  44. If `resource` is `nil`, the `placeholder` image will be set and
  45. `completionHandler` will be called with both `error` and `image` being `nil`.
  46. */
  47. @discardableResult
  48. public func setImage(with resource: Resource?,
  49. for state: UIControl.State,
  50. placeholder: UIImage? = nil,
  51. options: KingfisherOptionsInfo? = nil,
  52. progressBlock: DownloadProgressBlock? = nil,
  53. completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
  54. {
  55. guard let resource = resource else {
  56. base.setImage(placeholder, for: state)
  57. setWebURL(nil, for: state)
  58. completionHandler?(nil, nil, .none, nil)
  59. return .empty
  60. }
  61. let options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo)
  62. if !options.keepCurrentImageWhileLoading {
  63. base.setImage(placeholder, for: state)
  64. }
  65. setWebURL(resource.downloadURL, for: state)
  66. let task = KingfisherManager.shared.retrieveImage(
  67. with: resource,
  68. options: options,
  69. progressBlock: { receivedSize, totalSize in
  70. guard resource.downloadURL == self.webURL(for: state) else {
  71. return
  72. }
  73. if let progressBlock = progressBlock {
  74. progressBlock(receivedSize, totalSize)
  75. }
  76. },
  77. completionHandler: {[weak base] image, error, cacheType, imageURL in
  78. DispatchQueue.main.safeAsync {
  79. guard let strongBase = base, imageURL == self.webURL(for: state) else {
  80. completionHandler?(image, error, cacheType, imageURL)
  81. return
  82. }
  83. self.setImageTask(nil)
  84. if image != nil {
  85. strongBase.setImage(image, for: state)
  86. }
  87. completionHandler?(image, error, cacheType, imageURL)
  88. }
  89. })
  90. setImageTask(task)
  91. return task
  92. }
  93. /**
  94. Cancel the image download task bounded to the image view if it is running.
  95. Nothing will happen if the downloading has already finished.
  96. */
  97. public func cancelImageDownloadTask() {
  98. imageTask?.cancel()
  99. }
  100. /**
  101. Set the background image to use for a specified state with a resource,
  102. a placeholder image, options progress handler and completion handler.
  103. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
  104. - parameter state: The state that uses the specified image.
  105. - parameter placeholder: A placeholder image when retrieving the image at URL.
  106. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  107. - parameter progressBlock: Called when the image downloading progress gets updated.
  108. - parameter completionHandler: Called when the image retrieved and set.
  109. - returns: A task represents the retrieving process.
  110. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
  111. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
  112. If `resource` is `nil`, the `placeholder` image will be set and
  113. `completionHandler` will be called with both `error` and `image` being `nil`.
  114. */
  115. @discardableResult
  116. public func setBackgroundImage(with resource: Resource?,
  117. for state: UIControl.State,
  118. placeholder: UIImage? = nil,
  119. options: KingfisherOptionsInfo? = nil,
  120. progressBlock: DownloadProgressBlock? = nil,
  121. completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
  122. {
  123. guard let resource = resource else {
  124. base.setBackgroundImage(placeholder, for: state)
  125. setBackgroundWebURL(nil, for: state)
  126. completionHandler?(nil, nil, .none, nil)
  127. return .empty
  128. }
  129. let options = KingfisherManager.shared.defaultOptions + (options ?? KingfisherEmptyOptionsInfo)
  130. if !options.keepCurrentImageWhileLoading {
  131. base.setBackgroundImage(placeholder, for: state)
  132. }
  133. setBackgroundWebURL(resource.downloadURL, for: state)
  134. let task = KingfisherManager.shared.retrieveImage(
  135. with: resource,
  136. options: options,
  137. progressBlock: { receivedSize, totalSize in
  138. guard resource.downloadURL == self.backgroundWebURL(for: state) else {
  139. return
  140. }
  141. if let progressBlock = progressBlock {
  142. progressBlock(receivedSize, totalSize)
  143. }
  144. },
  145. completionHandler: { [weak base] image, error, cacheType, imageURL in
  146. DispatchQueue.main.safeAsync {
  147. guard let strongBase = base, imageURL == self.backgroundWebURL(for: state) else {
  148. completionHandler?(image, error, cacheType, imageURL)
  149. return
  150. }
  151. self.setBackgroundImageTask(nil)
  152. if image != nil {
  153. strongBase.setBackgroundImage(image, for: state)
  154. }
  155. completionHandler?(image, error, cacheType, imageURL)
  156. }
  157. })
  158. setBackgroundImageTask(task)
  159. return task
  160. }
  161. /**
  162. Cancel the background image download task bounded to the image view if it is running.
  163. Nothing will happen if the downloading has already finished.
  164. */
  165. public func cancelBackgroundImageDownloadTask() {
  166. backgroundImageTask?.cancel()
  167. }
  168. }
  169. // MARK: - Associated Object
  170. private var lastURLKey: Void?
  171. private var imageTaskKey: Void?
  172. extension Kingfisher where Base: UIButton {
  173. /**
  174. Get the image URL binded to this button for a specified state.
  175. - parameter state: The state that uses the specified image.
  176. - returns: Current URL for image.
  177. */
  178. public func webURL(for state: UIControl.State) -> URL? {
  179. return webURLs[NSNumber(value:state.rawValue)] as? URL
  180. }
  181. fileprivate func setWebURL(_ url: URL?, for state: UIControl.State) {
  182. webURLs[NSNumber(value:state.rawValue)] = url
  183. }
  184. fileprivate var webURLs: NSMutableDictionary {
  185. var dictionary = objc_getAssociatedObject(base, &lastURLKey) as? NSMutableDictionary
  186. if dictionary == nil {
  187. dictionary = NSMutableDictionary()
  188. setWebURLs(dictionary!)
  189. }
  190. return dictionary!
  191. }
  192. fileprivate func setWebURLs(_ URLs: NSMutableDictionary) {
  193. objc_setAssociatedObject(base, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  194. }
  195. fileprivate var imageTask: RetrieveImageTask? {
  196. return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
  197. }
  198. fileprivate func setImageTask(_ task: RetrieveImageTask?) {
  199. objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  200. }
  201. }
  202. private var lastBackgroundURLKey: Void?
  203. private var backgroundImageTaskKey: Void?
  204. extension Kingfisher where Base: UIButton {
  205. /**
  206. Get the background image URL binded to this button for a specified state.
  207. - parameter state: The state that uses the specified background image.
  208. - returns: Current URL for background image.
  209. */
  210. public func backgroundWebURL(for state: UIControl.State) -> URL? {
  211. return backgroundWebURLs[NSNumber(value:state.rawValue)] as? URL
  212. }
  213. fileprivate func setBackgroundWebURL(_ url: URL?, for state: UIControl.State) {
  214. backgroundWebURLs[NSNumber(value:state.rawValue)] = url
  215. }
  216. fileprivate var backgroundWebURLs: NSMutableDictionary {
  217. var dictionary = objc_getAssociatedObject(base, &lastBackgroundURLKey) as? NSMutableDictionary
  218. if dictionary == nil {
  219. dictionary = NSMutableDictionary()
  220. setBackgroundWebURLs(dictionary!)
  221. }
  222. return dictionary!
  223. }
  224. fileprivate func setBackgroundWebURLs(_ URLs: NSMutableDictionary) {
  225. objc_setAssociatedObject(base, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  226. }
  227. fileprivate var backgroundImageTask: RetrieveImageTask? {
  228. return objc_getAssociatedObject(base, &backgroundImageTaskKey) as? RetrieveImageTask
  229. }
  230. fileprivate func setBackgroundImageTask(_ task: RetrieveImageTask?) {
  231. objc_setAssociatedObject(base, &backgroundImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  232. }
  233. }