ImageDownloader.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. // ImageDownloader.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. #if os(iOS) || os(tvOS) || os(watchOS)
  25. import UIKit
  26. #elseif os(OSX)
  27. import Cocoa
  28. #endif
  29. /// The `RequestReceipt` is an object vended by the `ImageDownloader` when starting a download request. It can be used
  30. /// to cancel active requests running on the `ImageDownloader` session. As a general rule, image download requests
  31. /// should be cancelled using the `RequestReceipt` instead of calling `cancel` directly on the `request` itself. The
  32. /// `ImageDownloader` is optimized to handle duplicate request scenarios as well as pending versus active downloads.
  33. public class RequestReceipt {
  34. /// The download request created by the `ImageDownloader`.
  35. public let request: Request
  36. /// The unique identifier for the image filters and completion handlers when duplicate requests are made.
  37. public let receiptID: String
  38. init(request: Request, receiptID: String) {
  39. self.request = request
  40. self.receiptID = receiptID
  41. }
  42. }
  43. /// The `ImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming
  44. /// downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded
  45. /// image is cached in the underlying `NSURLCache` as well as the in-memory image cache that supports image filters.
  46. /// By default, any download request with a cached image equivalent in the image cache will automatically be served the
  47. /// cached image representation. Additional advanced features include supporting multiple image filters and completion
  48. /// handlers for a single request.
  49. public class ImageDownloader {
  50. /// The completion handler closure used when an image download completes.
  51. public typealias CompletionHandler = Response<Image, NSError> -> Void
  52. /**
  53. Defines the order prioritization of incoming download requests being inserted into the queue.
  54. - FIFO: All incoming downloads are added to the back of the queue.
  55. - LIFO: All incoming downloads are added to the front of the queue.
  56. */
  57. public enum DownloadPrioritization {
  58. case FIFO, LIFO
  59. }
  60. class ResponseHandler {
  61. let identifier: String
  62. let request: Request
  63. var operations: [(id: String, filter: ImageFilter?, completion: CompletionHandler?)]
  64. init(request: Request, id: String, filter: ImageFilter?, completion: CompletionHandler?) {
  65. self.request = request
  66. self.identifier = ImageDownloader.identifierForURLRequest(request.request!)
  67. self.operations = [(id: id, filter: filter, completion: completion)]
  68. }
  69. }
  70. // MARK: - Properties
  71. /// The image cache used to store all downloaded images in.
  72. public let imageCache: ImageRequestCache?
  73. /// The credential used for authenticating each download request.
  74. public private(set) var credential: NSURLCredential?
  75. /// The underlying Alamofire `Manager` instance used to handle all download requests.
  76. public let sessionManager: Alamofire.Manager
  77. let downloadPrioritization: DownloadPrioritization
  78. let maximumActiveDownloads: Int
  79. var activeRequestCount = 0
  80. var queuedRequests: [Request] = []
  81. var responseHandlers: [String: ResponseHandler] = [:]
  82. private let synchronizationQueue: dispatch_queue_t = {
  83. let name = String(format: "com.alamofire.imagedownloader.synchronizationqueue-%08%08", arc4random(), arc4random())
  84. return dispatch_queue_create(name, DISPATCH_QUEUE_SERIAL)
  85. }()
  86. private let responseQueue: dispatch_queue_t = {
  87. let name = String(format: "com.alamofire.imagedownloader.responsequeue-%08%08", arc4random(), arc4random())
  88. return dispatch_queue_create(name, DISPATCH_QUEUE_CONCURRENT)
  89. }()
  90. // MARK: - Initialization
  91. /// The default instance of `ImageDownloader` initialized with default values.
  92. public static let defaultInstance = ImageDownloader()
  93. /**
  94. Creates a default `NSURLSessionConfiguration` with common usage parameter values.
  95. - returns: The default `NSURLSessionConfiguration` instance.
  96. */
  97. public class func defaultURLSessionConfiguration() -> NSURLSessionConfiguration {
  98. let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  99. configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
  100. configuration.HTTPShouldSetCookies = true
  101. configuration.HTTPShouldUsePipelining = false
  102. configuration.requestCachePolicy = .UseProtocolCachePolicy
  103. configuration.allowsCellularAccess = true
  104. configuration.timeoutIntervalForRequest = 60
  105. configuration.URLCache = ImageDownloader.defaultURLCache()
  106. return configuration
  107. }
  108. /**
  109. Creates a default `NSURLCache` with common usage parameter values.
  110. - returns: The default `NSURLCache` instance.
  111. */
  112. public class func defaultURLCache() -> NSURLCache {
  113. return NSURLCache(
  114. memoryCapacity: 20 * 1024 * 1024, // 20 MB
  115. diskCapacity: 150 * 1024 * 1024, // 150 MB
  116. diskPath: "com.alamofire.imagedownloader"
  117. )
  118. }
  119. /**
  120. Initializes the `ImageDownloader` instance with the given configuration, download prioritization, maximum active
  121. download count and image cache.
  122. - parameter configuration: The `NSURLSessionConfiguration` to use to create the underlying Alamofire
  123. `Manager` instance.
  124. - parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
  125. - parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
  126. - parameter imageCache: The image cache used to store all downloaded images in.
  127. - returns: The new `ImageDownloader` instance.
  128. */
  129. public init(
  130. configuration: NSURLSessionConfiguration = ImageDownloader.defaultURLSessionConfiguration(),
  131. downloadPrioritization: DownloadPrioritization = .FIFO,
  132. maximumActiveDownloads: Int = 4,
  133. imageCache: ImageRequestCache? = AutoPurgingImageCache())
  134. {
  135. self.sessionManager = Alamofire.Manager(configuration: configuration)
  136. self.sessionManager.startRequestsImmediately = false
  137. self.downloadPrioritization = downloadPrioritization
  138. self.maximumActiveDownloads = maximumActiveDownloads
  139. self.imageCache = imageCache
  140. }
  141. /**
  142. Initializes the `ImageDownloader` instance with the given sesion manager, download prioritization, maximum
  143. active download count and image cache.
  144. - parameter sessionManager: The Alamofire `Manager` instance to handle all download requests.
  145. - parameter downloadPrioritization: The download prioritization of the download queue. `.FIFO` by default.
  146. - parameter maximumActiveDownloads: The maximum number of active downloads allowed at any given time.
  147. - parameter imageCache: The image cache used to store all downloaded images in.
  148. - returns: The new `ImageDownloader` instance.
  149. */
  150. public init(
  151. sessionManager: Manager,
  152. downloadPrioritization: DownloadPrioritization = .FIFO,
  153. maximumActiveDownloads: Int = 4,
  154. imageCache: ImageRequestCache? = AutoPurgingImageCache())
  155. {
  156. self.sessionManager = sessionManager
  157. self.sessionManager.startRequestsImmediately = false
  158. self.downloadPrioritization = downloadPrioritization
  159. self.maximumActiveDownloads = maximumActiveDownloads
  160. self.imageCache = imageCache
  161. }
  162. // MARK: - Authentication
  163. /**
  164. Associates an HTTP Basic Auth credential with all future download requests.
  165. - parameter user: The user.
  166. - parameter password: The password.
  167. - parameter persistence: The URL credential persistence. `.ForSession` by default.
  168. */
  169. public func addAuthentication(
  170. user user: String,
  171. password: String,
  172. persistence: NSURLCredentialPersistence = .ForSession)
  173. {
  174. let credential = NSURLCredential(user: user, password: password, persistence: persistence)
  175. addAuthentication(usingCredential: credential)
  176. }
  177. /**
  178. Associates the specified credential with all future download requests.
  179. - parameter credential: The credential.
  180. */
  181. public func addAuthentication(usingCredential credential: NSURLCredential) {
  182. dispatch_sync(synchronizationQueue) {
  183. self.credential = credential
  184. }
  185. }
  186. // MARK: - Download
  187. /**
  188. Creates a download request using the internal Alamofire `Manager` instance for the specified URL request.
  189. If the same download request is already in the queue or currently being downloaded, the filter and completion
  190. handler are appended to the already existing request. Once the request completes, all filters and completion
  191. handlers attached to the request are executed in the order they were added. Additionally, any filters attached
  192. to the request with the same identifiers are only executed once. The resulting image is then passed into each
  193. completion handler paired with the filter.
  194. You should not attempt to directly cancel the `request` inside the request receipt since other callers may be
  195. relying on the completion of that request. Instead, you should call `cancelRequestForRequestReceipt` with the
  196. returned request receipt to allow the `ImageDownloader` to optimize the cancellation on behalf of all active
  197. callers.
  198. - parameter URLRequest: The URL request.
  199. - parameter filter The image filter to apply to the image after the download is complete. Defaults to `nil`.
  200. - parameter completion: The closure called when the download request is complete.
  201. - returns: The request receipt for the download request if available. `nil` if the image is stored in the image
  202. cache and the URL request cache policy allows the cache to be used.
  203. */
  204. public func downloadImage(
  205. URLRequest URLRequest: URLRequestConvertible,
  206. filter: ImageFilter? = nil,
  207. completion: CompletionHandler? = nil)
  208. -> RequestReceipt?
  209. {
  210. return downloadImage(
  211. URLRequest: URLRequest,
  212. receiptID: NSUUID().UUIDString,
  213. filter: filter,
  214. completion: completion
  215. )
  216. }
  217. func downloadImage(
  218. URLRequest URLRequest: URLRequestConvertible,
  219. receiptID: String,
  220. filter: ImageFilter?,
  221. completion: CompletionHandler?)
  222. -> RequestReceipt?
  223. {
  224. var request: Request!
  225. dispatch_sync(synchronizationQueue) {
  226. // 1) Append the filter and completion handler to a pre-existing request if it already exists
  227. let identifier = ImageDownloader.identifierForURLRequest(URLRequest)
  228. if let responseHandler = self.responseHandlers[identifier] {
  229. responseHandler.operations.append(id: receiptID, filter: filter, completion: completion)
  230. request = responseHandler.request
  231. return
  232. }
  233. // 2) Attempt to load the image from the image cache if the cache policy allows it
  234. switch URLRequest.URLRequest.cachePolicy {
  235. case .UseProtocolCachePolicy, .ReturnCacheDataElseLoad, .ReturnCacheDataDontLoad:
  236. if let image = self.imageCache?.imageForRequest(
  237. URLRequest.URLRequest,
  238. withAdditionalIdentifier: filter?.identifier)
  239. {
  240. dispatch_async(dispatch_get_main_queue()) {
  241. let response = Response<Image, NSError>(
  242. request: URLRequest.URLRequest,
  243. response: nil,
  244. data: nil,
  245. result: .Success(image)
  246. )
  247. completion?(response)
  248. }
  249. return
  250. }
  251. default:
  252. break
  253. }
  254. // 3) Create the request and set up authentication, validation and response serialization
  255. request = self.sessionManager.request(URLRequest)
  256. if let credential = self.credential {
  257. request.authenticate(usingCredential: credential)
  258. }
  259. request.validate()
  260. request.response(
  261. queue: self.responseQueue,
  262. responseSerializer: Request.imageResponseSerializer(),
  263. completionHandler: { [weak self] response in
  264. guard let strongSelf = self, let request = response.request else { return }
  265. let responseHandler = strongSelf.safelyRemoveResponseHandlerWithIdentifier(identifier)
  266. switch response.result {
  267. case .Success(let image):
  268. var filteredImages: [String: Image] = [:]
  269. for (_, filter, completion) in responseHandler.operations {
  270. var filteredImage: Image
  271. if let filter = filter {
  272. if let alreadyFilteredImage = filteredImages[filter.identifier] {
  273. filteredImage = alreadyFilteredImage
  274. } else {
  275. filteredImage = filter.filter(image)
  276. filteredImages[filter.identifier] = filteredImage
  277. }
  278. } else {
  279. filteredImage = image
  280. }
  281. strongSelf.imageCache?.addImage(
  282. filteredImage,
  283. forRequest: request,
  284. withAdditionalIdentifier: filter?.identifier
  285. )
  286. dispatch_async(dispatch_get_main_queue()) {
  287. let response = Response<Image, NSError>(
  288. request: response.request,
  289. response: response.response,
  290. data: response.data,
  291. result: .Success(filteredImage),
  292. timeline: response.timeline
  293. )
  294. completion?(response)
  295. }
  296. }
  297. case .Failure:
  298. for (_, _, completion) in responseHandler.operations {
  299. dispatch_async(dispatch_get_main_queue()) { completion?(response) }
  300. }
  301. }
  302. strongSelf.safelyDecrementActiveRequestCount()
  303. strongSelf.safelyStartNextRequestIfNecessary()
  304. }
  305. )
  306. // 4) Store the response handler for use when the request completes
  307. let responseHandler = ResponseHandler(
  308. request: request,
  309. id: receiptID,
  310. filter: filter,
  311. completion: completion
  312. )
  313. self.responseHandlers[identifier] = responseHandler
  314. // 5) Either start the request or enqueue it depending on the current active request count
  315. if self.isActiveRequestCountBelowMaximumLimit() {
  316. self.startRequest(request)
  317. } else {
  318. self.enqueueRequest(request)
  319. }
  320. }
  321. if let request = request {
  322. return RequestReceipt(request: request, receiptID: receiptID)
  323. }
  324. return nil
  325. }
  326. /**
  327. Creates a download request using the internal Alamofire `Manager` instance for each specified URL request.
  328. For each request, if the same download request is already in the queue or currently being downloaded, the
  329. filter and completion handler are appended to the already existing request. Once the request completes, all
  330. filters and completion handlers attached to the request are executed in the order they were added.
  331. Additionally, any filters attached to the request with the same identifiers are only executed once. The
  332. resulting image is then passed into each completion handler paired with the filter.
  333. You should not attempt to directly cancel any of the `request`s inside the request receipts array since other
  334. callers may be relying on the completion of that request. Instead, you should call
  335. `cancelRequestForRequestReceipt` with the returned request receipt to allow the `ImageDownloader` to optimize
  336. the cancellation on behalf of all active callers.
  337. - parameter URLRequests: The URL requests.
  338. - parameter filter The image filter to apply to the image after each download is complete.
  339. - parameter completion: The closure called when each download request is complete.
  340. - returns: The request receipts for the download requests if available. If an image is stored in the image
  341. cache and the URL request cache policy allows the cache to be used, a receipt will not be returned
  342. for that request.
  343. */
  344. public func downloadImages(
  345. URLRequests URLRequests: [URLRequestConvertible],
  346. filter: ImageFilter? = nil,
  347. completion: CompletionHandler? = nil)
  348. -> [RequestReceipt]
  349. {
  350. return URLRequests.flatMap { downloadImage(URLRequest: $0, filter: filter, completion: completion) }
  351. }
  352. /**
  353. Cancels the request in the receipt by removing the response handler and cancelling the request if necessary.
  354. If the request is pending in the queue, it will be cancelled if no other response handlers are registered with
  355. the request. If the request is currently executing or is already completed, the response handler is removed and
  356. will not be called.
  357. - parameter requestReceipt: The request receipt to cancel.
  358. */
  359. public func cancelRequestForRequestReceipt(requestReceipt: RequestReceipt) {
  360. dispatch_sync(synchronizationQueue) {
  361. let identifier = ImageDownloader.identifierForURLRequest(requestReceipt.request.request!)
  362. guard let responseHandler = self.responseHandlers[identifier] else { return }
  363. if let index = responseHandler.operations.indexOf({ $0.id == requestReceipt.receiptID }) {
  364. let operation = responseHandler.operations.removeAtIndex(index)
  365. let response: Response<Image, NSError> = {
  366. let URLRequest = requestReceipt.request.request!
  367. let error: NSError = {
  368. let failureReason = "ImageDownloader cancelled URL request: \(URLRequest.URLString)"
  369. let userInfo = [NSLocalizedFailureReasonErrorKey: failureReason]
  370. return NSError(domain: Error.Domain, code: NSURLErrorCancelled, userInfo: userInfo)
  371. }()
  372. return Response(request: URLRequest, response: nil, data: nil, result: .Failure(error))
  373. }()
  374. dispatch_async(dispatch_get_main_queue()) { operation.completion?(response) }
  375. }
  376. if responseHandler.operations.isEmpty && requestReceipt.request.task.state == .Suspended {
  377. requestReceipt.request.cancel()
  378. }
  379. }
  380. }
  381. // MARK: - Internal - Thread-Safe Request Methods
  382. func safelyRemoveResponseHandlerWithIdentifier(identifier: String) -> ResponseHandler {
  383. var responseHandler: ResponseHandler!
  384. dispatch_sync(synchronizationQueue) {
  385. responseHandler = self.responseHandlers.removeValueForKey(identifier)
  386. }
  387. return responseHandler
  388. }
  389. func safelyStartNextRequestIfNecessary() {
  390. dispatch_sync(synchronizationQueue) {
  391. guard self.isActiveRequestCountBelowMaximumLimit() else { return }
  392. while (!self.queuedRequests.isEmpty) {
  393. if let request = self.dequeueRequest() where request.task.state == .Suspended {
  394. self.startRequest(request)
  395. break
  396. }
  397. }
  398. }
  399. }
  400. func safelyDecrementActiveRequestCount() {
  401. dispatch_sync(self.synchronizationQueue) {
  402. if self.activeRequestCount > 0 {
  403. self.activeRequestCount -= 1
  404. }
  405. }
  406. }
  407. // MARK: - Internal - Non Thread-Safe Request Methods
  408. func startRequest(request: Request) {
  409. request.resume()
  410. activeRequestCount += 1
  411. }
  412. func enqueueRequest(request: Request) {
  413. switch downloadPrioritization {
  414. case .FIFO:
  415. queuedRequests.append(request)
  416. case .LIFO:
  417. queuedRequests.insert(request, atIndex: 0)
  418. }
  419. }
  420. func dequeueRequest() -> Request? {
  421. var request: Request?
  422. if !queuedRequests.isEmpty {
  423. request = queuedRequests.removeFirst()
  424. }
  425. return request
  426. }
  427. func isActiveRequestCountBelowMaximumLimit() -> Bool {
  428. return activeRequestCount < maximumActiveDownloads
  429. }
  430. static func identifierForURLRequest(URLRequest: URLRequestConvertible) -> String {
  431. return URLRequest.URLRequest.URLString
  432. }
  433. }