UIImageView+AlamofireImage.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // UIImageView+AlamofireImage.swift
  2. //
  3. // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Alamofire
  23. import Foundation
  24. import UIKit
  25. extension UIImageView {
  26. // MARK: - ImageTransition
  27. /// Used to wrap all `UIView` animation transition options alongside a duration.
  28. public enum ImageTransition {
  29. case None
  30. case CrossDissolve(NSTimeInterval)
  31. case CurlDown(NSTimeInterval)
  32. case CurlUp(NSTimeInterval)
  33. case FlipFromBottom(NSTimeInterval)
  34. case FlipFromLeft(NSTimeInterval)
  35. case FlipFromRight(NSTimeInterval)
  36. case FlipFromTop(NSTimeInterval)
  37. case Custom(
  38. duration: NSTimeInterval,
  39. animationOptions: UIViewAnimationOptions,
  40. animations: (UIImageView, Image) -> Void,
  41. completion: (Bool -> Void)?
  42. )
  43. /// The duration of the image transition in seconds.
  44. public var duration: NSTimeInterval {
  45. switch self {
  46. case None:
  47. return 0.0
  48. case CrossDissolve(let duration):
  49. return duration
  50. case CurlDown(let duration):
  51. return duration
  52. case CurlUp(let duration):
  53. return duration
  54. case FlipFromBottom(let duration):
  55. return duration
  56. case FlipFromLeft(let duration):
  57. return duration
  58. case FlipFromRight(let duration):
  59. return duration
  60. case FlipFromTop(let duration):
  61. return duration
  62. case Custom(let duration, _, _, _):
  63. return duration
  64. }
  65. }
  66. /// The animation options of the image transition.
  67. public var animationOptions: UIViewAnimationOptions {
  68. switch self {
  69. case None:
  70. return .TransitionNone
  71. case CrossDissolve:
  72. return .TransitionCrossDissolve
  73. case CurlDown:
  74. return .TransitionCurlDown
  75. case CurlUp:
  76. return .TransitionCurlUp
  77. case FlipFromBottom:
  78. return .TransitionFlipFromBottom
  79. case FlipFromLeft:
  80. return .TransitionFlipFromLeft
  81. case FlipFromRight:
  82. return .TransitionFlipFromRight
  83. case FlipFromTop:
  84. return .TransitionFlipFromTop
  85. case Custom(_, let animationOptions, _, _):
  86. return animationOptions
  87. }
  88. }
  89. /// The animation options of the image transition.
  90. public var animations: ((UIImageView, Image) -> Void) {
  91. switch self {
  92. case Custom(_, _, let animations, _):
  93. return animations
  94. default:
  95. return { $0.image = $1 }
  96. }
  97. }
  98. /// The completion closure associated with the image transition.
  99. public var completion: (Bool -> Void)? {
  100. switch self {
  101. case Custom(_, _, _, let completion):
  102. return completion
  103. default:
  104. return nil
  105. }
  106. }
  107. }
  108. // MARK: - Private - AssociatedKeys
  109. private struct AssociatedKeys {
  110. static var ImageDownloaderKey = "af_UIImageView.ImageDownloader"
  111. static var SharedImageDownloaderKey = "af_UIImageView.SharedImageDownloader"
  112. static var ActiveRequestReceiptKey = "af_UIImageView.ActiveRequestReceipt"
  113. }
  114. // MARK: - Associated Properties
  115. /// The instance image downloader used to download all images. If this property is `nil`, the `UIImageView` will
  116. /// fallback on the `af_sharedImageDownloader` for all downloads. The most common use case for needing to use a
  117. /// custom instance image downloader is when images are behind different basic auth credentials.
  118. public var af_imageDownloader: ImageDownloader? {
  119. get {
  120. return objc_getAssociatedObject(self, &AssociatedKeys.ImageDownloaderKey) as? ImageDownloader
  121. }
  122. set(downloader) {
  123. objc_setAssociatedObject(self, &AssociatedKeys.ImageDownloaderKey, downloader, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  124. }
  125. }
  126. /// The shared image downloader used to download all images. By default, this is the default `ImageDownloader`
  127. /// instance backed with an `AutoPurgingImageCache` which automatically evicts images from the cache when the memory
  128. /// capacity is reached or memory warning notifications occur. The shared image downloader is only used if the
  129. /// `af_imageDownloader` is `nil`.
  130. public class var af_sharedImageDownloader: ImageDownloader {
  131. get {
  132. if let downloader = objc_getAssociatedObject(self, &AssociatedKeys.SharedImageDownloaderKey) as? ImageDownloader {
  133. return downloader
  134. } else {
  135. return ImageDownloader.defaultInstance
  136. }
  137. }
  138. set {
  139. objc_setAssociatedObject(self, &AssociatedKeys.SharedImageDownloaderKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  140. }
  141. }
  142. var af_activeRequestReceipt: RequestReceipt? {
  143. get {
  144. return objc_getAssociatedObject(self, &AssociatedKeys.ActiveRequestReceiptKey) as? RequestReceipt
  145. }
  146. set {
  147. objc_setAssociatedObject(self, &AssociatedKeys.ActiveRequestReceiptKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  148. }
  149. }
  150. // MARK: - Image Download
  151. /**
  152. Asynchronously downloads an image from the specified URL, applies the specified image filter to the downloaded
  153. image and sets it once finished while executing the image transition.
  154. If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
  155. set immediately, and then the remote image will be set once the image request is finished.
  156. The `completion` closure is called after the image download and filtering are complete, but before the start of
  157. the image transition. Please note it is no longer the responsibility of the `completion` closure to set the
  158. image. It will be set automatically. If you require a second notification after the image transition completes,
  159. use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when
  160. the image transition is finished.
  161. - parameter URL: The URL used for the image request.
  162. - parameter placeholderImage: The image to be set initially until the image request finished. If
  163. `nil`, the image view will not change its image until the image
  164. request finishes. Defaults to `nil`.
  165. - parameter filter: The image filter applied to the image after the image request is
  166. finished. Defaults to `nil`.
  167. - parameter imageTransition: The image transition animation applied to the image when set.
  168. Defaults to `.None`.
  169. - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults
  170. to `false`.
  171. - parameter completion: A closure to be executed when the image request finishes. The closure
  172. has no return value and takes three arguments: the original request,
  173. the response from the server and the result containing either the
  174. image or the error that occurred. If the image was returned from the
  175. image cache, the response will be `nil`. Defaults to `nil`.
  176. */
  177. public func af_setImageWithURL(
  178. URL: NSURL,
  179. placeholderImage: UIImage? = nil,
  180. filter: ImageFilter? = nil,
  181. imageTransition: ImageTransition = .None,
  182. runImageTransitionIfCached: Bool = false,
  183. completion: (Response<UIImage, NSError> -> Void)? = nil)
  184. {
  185. af_setImageWithURLRequest(
  186. URLRequestWithURL(URL),
  187. placeholderImage: placeholderImage,
  188. filter: filter,
  189. imageTransition: imageTransition,
  190. runImageTransitionIfCached: runImageTransitionIfCached,
  191. completion: completion
  192. )
  193. }
  194. /**
  195. Asynchronously downloads an image from the specified URL Request, applies the specified image filter to the downloaded
  196. image and sets it once finished while executing the image transition.
  197. If the image is cached locally, the image is set immediately. Otherwise the specified placehoder image will be
  198. set immediately, and then the remote image will be set once the image request is finished.
  199. The `completion` closure is called after the image download and filtering are complete, but before the start of
  200. the image transition. Please note it is no longer the responsibility of the `completion` closure to set the
  201. image. It will be set automatically. If you require a second notification after the image transition completes,
  202. use a `.Custom` image transition with a `completion` closure. The `.Custom` `completion` closure is called when
  203. the image transition is finished.
  204. - parameter URLRequest: The URL request.
  205. - parameter placeholderImage: The image to be set initially until the image request finished. If
  206. `nil`, the image view will not change its image until the image
  207. request finishes. Defaults to `nil`.
  208. - parameter filter: The image filter applied to the image after the image request is
  209. finished. Defaults to `nil`.
  210. - parameter imageTransition: The image transition animation applied to the image when set.
  211. Defaults to `.None`.
  212. - parameter runImageTransitionIfCached: Whether to run the image transition if the image is cached. Defaults
  213. to `false`.
  214. - parameter completion: A closure to be executed when the image request finishes. The closure
  215. has no return value and takes three arguments: the original request,
  216. the response from the server and the result containing either the
  217. image or the error that occurred. If the image was returned from the
  218. image cache, the response will be `nil`. Defaults to `nil`.
  219. */
  220. public func af_setImageWithURLRequest(
  221. URLRequest: URLRequestConvertible,
  222. placeholderImage: UIImage? = nil,
  223. filter: ImageFilter? = nil,
  224. imageTransition: ImageTransition = .None,
  225. runImageTransitionIfCached: Bool = false,
  226. completion: (Response<UIImage, NSError> -> Void)? = nil)
  227. {
  228. guard !isURLRequestURLEqualToActiveRequestURL(URLRequest) else { return }
  229. af_cancelImageRequest()
  230. let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader
  231. let imageCache = imageDownloader.imageCache
  232. // Use the image from the image cache if it exists
  233. if let image = imageCache?.imageForRequest(URLRequest.URLRequest, withAdditionalIdentifier: filter?.identifier) {
  234. let response = Response<UIImage, NSError>(
  235. request: URLRequest.URLRequest,
  236. response: nil,
  237. data: nil,
  238. result: .Success(image)
  239. )
  240. completion?(response)
  241. if runImageTransitionIfCached {
  242. let tinyDelay = dispatch_time(DISPATCH_TIME_NOW, Int64(0.001 * Float(NSEC_PER_SEC)))
  243. // Need to let the runloop cycle for the placeholder image to take affect
  244. dispatch_after(tinyDelay, dispatch_get_main_queue()) {
  245. self.runImageTransition(imageTransition, withImage: image)
  246. }
  247. } else {
  248. self.image = image
  249. }
  250. return
  251. }
  252. // Set the placeholder since we're going to have to download
  253. if let placeholderImage = placeholderImage { self.image = placeholderImage }
  254. // Generate a unique download id to check whether the active request has changed while downloading
  255. let downloadID = NSUUID().UUIDString
  256. // Download the image, then run the image transition or completion handler
  257. let requestReceipt = imageDownloader.downloadImage(
  258. URLRequest: URLRequest,
  259. receiptID: downloadID,
  260. filter: filter,
  261. completion: { [weak self] response in
  262. guard let strongSelf = self else { return }
  263. completion?(response)
  264. guard
  265. strongSelf.isURLRequestURLEqualToActiveRequestURL(response.request) &&
  266. strongSelf.af_activeRequestReceipt?.receiptID == downloadID
  267. else {
  268. return
  269. }
  270. if let image = response.result.value {
  271. strongSelf.runImageTransition(imageTransition, withImage: image)
  272. }
  273. strongSelf.af_activeRequestReceipt = nil
  274. }
  275. )
  276. af_activeRequestReceipt = requestReceipt
  277. }
  278. // MARK: - Image Download Cancellation
  279. /**
  280. Cancels the active download request, if one exists.
  281. */
  282. public func af_cancelImageRequest() {
  283. guard let activeRequestReceipt = af_activeRequestReceipt else { return }
  284. let imageDownloader = af_imageDownloader ?? UIImageView.af_sharedImageDownloader
  285. imageDownloader.cancelRequestForRequestReceipt(activeRequestReceipt)
  286. af_activeRequestReceipt = nil
  287. }
  288. // MARK: - Image Transition
  289. /**
  290. Runs the image transition on the image view with the specified image.
  291. - parameter imageTransition: The image transition to ran on the image view.
  292. - parameter image: The image to use for the image transition.
  293. */
  294. public func runImageTransition(imageTransition: ImageTransition, withImage image: Image) {
  295. UIView.transitionWithView(
  296. self,
  297. duration: imageTransition.duration,
  298. options: imageTransition.animationOptions,
  299. animations: {
  300. imageTransition.animations(self, image)
  301. },
  302. completion: imageTransition.completion
  303. )
  304. }
  305. // MARK: - Private - URL Request Helper Methods
  306. private func URLRequestWithURL(URL: NSURL) -> NSURLRequest {
  307. let mutableURLRequest = NSMutableURLRequest(URL: URL)
  308. for mimeType in Request.acceptableImageContentTypes {
  309. mutableURLRequest.addValue(mimeType, forHTTPHeaderField: "Accept")
  310. }
  311. return mutableURLRequest
  312. }
  313. private func isURLRequestURLEqualToActiveRequestURL(URLRequest: URLRequestConvertible?) -> Bool {
  314. if let
  315. currentRequest = af_activeRequestReceipt?.request.task.originalRequest
  316. where currentRequest.URLString == URLRequest?.URLRequest.URLString
  317. {
  318. return true
  319. }
  320. return false
  321. }
  322. }