UIButton+Kingfisher.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. //
  2. // UIButton+Kingfisher.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/13.
  6. //
  7. // Copyright (c) 2016 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(iOS) || os(tvOS)
  27. import UIKit
  28. /**
  29. * Set image to use from web for a specified state.
  30. */
  31. extension UIButton {
  32. /**
  33. Set an image to use for a specified state with a URL, a placeholder image, options, progress handler and completion handler.
  34. - parameter URL: The URL of image for specified state.
  35. - parameter state: The state that uses the specified image.
  36. - parameter placeholderImage: A placeholder image when retrieving the image at URL.
  37. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  38. - parameter progressBlock: Called when the image downloading progress gets updated.
  39. - parameter completionHandler: Called when the image retrieved and set.
  40. - returns: A task represents the retrieving process.
  41. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
  42. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
  43. */
  44. public func kf_setImageWithURL(URL: NSURL,
  45. forState state: UIControlState,
  46. placeholderImage: UIImage?,
  47. optionsInfo: KingfisherOptionsInfo?,
  48. progressBlock: DownloadProgressBlock?,
  49. completionHandler: CompletionHandler?) -> RetrieveImageTask
  50. {
  51. return kf_setImageWithResource(Resource(downloadURL: URL),
  52. forState: state,
  53. placeholderImage: placeholderImage,
  54. optionsInfo: optionsInfo,
  55. progressBlock: progressBlock,
  56. completionHandler: completionHandler)
  57. }
  58. /**
  59. Set an image to use for a specified state with a resource, a placeholder image, options, progress handler and completion handler.
  60. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
  61. - parameter state: The state that uses the specified image.
  62. - parameter placeholderImage: A placeholder image when retrieving the image at URL.
  63. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  64. - parameter progressBlock: Called when the image downloading progress gets updated.
  65. - parameter completionHandler: Called when the image retrieved and set.
  66. - returns: A task represents the retrieving process.
  67. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
  68. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
  69. */
  70. public func kf_setImageWithResource(resource: Resource,
  71. forState state: UIControlState,
  72. placeholderImage: UIImage?,
  73. optionsInfo: KingfisherOptionsInfo?,
  74. progressBlock: DownloadProgressBlock?,
  75. completionHandler: CompletionHandler?) -> RetrieveImageTask
  76. {
  77. setImage(placeholderImage, forState: state)
  78. kf_setWebURL(resource.downloadURL, forState: state)
  79. let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
  80. progressBlock: { receivedSize, totalSize in
  81. if let progressBlock = progressBlock {
  82. progressBlock(receivedSize: receivedSize, totalSize: totalSize)
  83. }
  84. },
  85. completionHandler: {[weak self] image, error, cacheType, imageURL in
  86. dispatch_async_safely_to_main_queue {
  87. if let sSelf = self {
  88. sSelf.kf_setImageTask(nil)
  89. if imageURL == sSelf.kf_webURLForState(state) && image != nil {
  90. sSelf.setImage(image, forState: state)
  91. }
  92. completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
  93. }
  94. }
  95. })
  96. kf_setImageTask(task)
  97. return task
  98. }
  99. }
  100. private var lastURLKey: Void?
  101. private var imageTaskKey: Void?
  102. // MARK: - Runtime for UIButton image
  103. extension UIButton {
  104. /**
  105. Get the image URL binded to this button for a specified state.
  106. - parameter state: The state that uses the specified image.
  107. - returns: Current URL for image.
  108. */
  109. public func kf_webURLForState(state: UIControlState) -> NSURL? {
  110. return kf_webURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
  111. }
  112. private func kf_setWebURL(URL: NSURL, forState state: UIControlState) {
  113. kf_webURLs[NSNumber(unsignedLong:state.rawValue)] = URL
  114. }
  115. private var kf_webURLs: NSMutableDictionary {
  116. var dictionary = objc_getAssociatedObject(self, &lastURLKey) as? NSMutableDictionary
  117. if dictionary == nil {
  118. dictionary = NSMutableDictionary()
  119. kf_setWebURLs(dictionary!)
  120. }
  121. return dictionary!
  122. }
  123. private func kf_setWebURLs(URLs: NSMutableDictionary) {
  124. objc_setAssociatedObject(self, &lastURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  125. }
  126. private var kf_imageTask: RetrieveImageTask? {
  127. return objc_getAssociatedObject(self, &imageTaskKey) as? RetrieveImageTask
  128. }
  129. private func kf_setImageTask(task: RetrieveImageTask?) {
  130. objc_setAssociatedObject(self, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  131. }
  132. }
  133. /**
  134. * Set background image to use from web for a specified state.
  135. */
  136. extension UIButton {
  137. /**
  138. Set the background image to use for a specified state with a URL,
  139. a placeholder image, options progress handler and completion handler.
  140. - parameter URL: The URL of image for specified state.
  141. - parameter state: The state that uses the specified image.
  142. - parameter placeholderImage: A placeholder image when retrieving the image at URL.
  143. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  144. - parameter progressBlock: Called when the image downloading progress gets updated.
  145. - parameter completionHandler: Called when the image retrieved and set.
  146. - returns: A task represents the retrieving process.
  147. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
  148. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
  149. */
  150. public func kf_setBackgroundImageWithURL(URL: NSURL,
  151. forState state: UIControlState,
  152. placeholderImage: UIImage?,
  153. optionsInfo: KingfisherOptionsInfo?,
  154. progressBlock: DownloadProgressBlock?,
  155. completionHandler: CompletionHandler?) -> RetrieveImageTask
  156. {
  157. return kf_setBackgroundImageWithResource(Resource(downloadURL: URL),
  158. forState: state,
  159. placeholderImage: placeholderImage,
  160. optionsInfo: optionsInfo,
  161. progressBlock: progressBlock,
  162. completionHandler: completionHandler)
  163. }
  164. /**
  165. Set the background image to use for a specified state with a resource,
  166. a placeholder image, options progress handler and completion handler.
  167. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
  168. - parameter state: The state that uses the specified image.
  169. - parameter placeholderImage: A placeholder image when retrieving the image at URL.
  170. - parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  171. - parameter progressBlock: Called when the image downloading progress gets updated.
  172. - parameter completionHandler: Called when the image retrieved and set.
  173. - returns: A task represents the retrieving process.
  174. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
  175. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
  176. */
  177. public func kf_setBackgroundImageWithResource(resource: Resource,
  178. forState state: UIControlState,
  179. placeholderImage: UIImage?,
  180. optionsInfo: KingfisherOptionsInfo?,
  181. progressBlock: DownloadProgressBlock?,
  182. completionHandler: CompletionHandler?) -> RetrieveImageTask
  183. {
  184. setBackgroundImage(placeholderImage, forState: state)
  185. kf_setBackgroundWebURL(resource.downloadURL, forState: state)
  186. let task = KingfisherManager.sharedManager.retrieveImageWithResource(resource, optionsInfo: optionsInfo,
  187. progressBlock: { receivedSize, totalSize in
  188. if let progressBlock = progressBlock {
  189. progressBlock(receivedSize: receivedSize, totalSize: totalSize)
  190. }
  191. },
  192. completionHandler: { [weak self] image, error, cacheType, imageURL in
  193. dispatch_async_safely_to_main_queue {
  194. if let sSelf = self {
  195. sSelf.kf_setBackgroundImageTask(nil)
  196. if imageURL == sSelf.kf_backgroundWebURLForState(state) && image != nil {
  197. sSelf.setBackgroundImage(image, forState: state)
  198. }
  199. completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
  200. }
  201. }
  202. })
  203. kf_setBackgroundImageTask(task)
  204. return task
  205. }
  206. }
  207. private var lastBackgroundURLKey: Void?
  208. private var backgroundImageTaskKey: Void?
  209. // MARK: - Runtime for UIButton background image
  210. extension UIButton {
  211. /**
  212. Get the background image URL binded to this button for a specified state.
  213. - parameter state: The state that uses the specified background image.
  214. - returns: Current URL for background image.
  215. */
  216. public func kf_backgroundWebURLForState(state: UIControlState) -> NSURL? {
  217. return kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] as? NSURL
  218. }
  219. private func kf_setBackgroundWebURL(URL: NSURL, forState state: UIControlState) {
  220. kf_backgroundWebURLs[NSNumber(unsignedLong:state.rawValue)] = URL
  221. }
  222. private var kf_backgroundWebURLs: NSMutableDictionary {
  223. var dictionary = objc_getAssociatedObject(self, &lastBackgroundURLKey) as? NSMutableDictionary
  224. if dictionary == nil {
  225. dictionary = NSMutableDictionary()
  226. kf_setBackgroundWebURLs(dictionary!)
  227. }
  228. return dictionary!
  229. }
  230. private func kf_setBackgroundWebURLs(URLs: NSMutableDictionary) {
  231. objc_setAssociatedObject(self, &lastBackgroundURLKey, URLs, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  232. }
  233. private var kf_backgroundImageTask: RetrieveImageTask? {
  234. return objc_getAssociatedObject(self, &backgroundImageTaskKey) as? RetrieveImageTask
  235. }
  236. private func kf_setBackgroundImageTask(task: RetrieveImageTask?) {
  237. objc_setAssociatedObject(self, &backgroundImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  238. }
  239. }
  240. // MARK: - Cancel image download tasks.
  241. extension UIButton {
  242. /**
  243. Cancel the image download task bounded to the image view if it is running.
  244. Nothing will happen if the downloading has already finished.
  245. */
  246. public func kf_cancelImageDownloadTask() {
  247. kf_imageTask?.downloadTask?.cancel()
  248. }
  249. /**
  250. Cancel the background image download task bounded to the image view if it is running.
  251. Nothing will happen if the downloading has already finished.
  252. */
  253. public func kf_cancelBackgroundImageDownloadTask() {
  254. kf_backgroundImageTask?.downloadTask?.cancel()
  255. }
  256. }
  257. #elseif os(OSX)
  258. import AppKit
  259. extension NSButton {
  260. // Not Implemented yet.
  261. }
  262. #endif