ImageDownloader.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. //
  2. // ImageDownloader.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  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(macOS)
  27. import AppKit
  28. #else
  29. import UIKit
  30. #endif
  31. /// Progress update block of downloader.
  32. public typealias ImageDownloaderProgressBlock = DownloadProgressBlock
  33. /// Completion block of downloader.
  34. public typealias ImageDownloaderCompletionHandler = ((image: Image?, error: NSError?, url: URL?, originalData: Data?) -> ())
  35. /// Download task.
  36. public struct RetrieveImageDownloadTask {
  37. let internalTask: URLSessionDataTask
  38. /// Downloader by which this task is intialized.
  39. public private(set) weak var ownerDownloader: ImageDownloader?
  40. /**
  41. Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error.
  42. */
  43. public func cancel() {
  44. ownerDownloader?.cancelDownloadingTask(self)
  45. }
  46. /// The original request URL of this download task.
  47. public var url: URL? {
  48. return internalTask.originalRequest?.url
  49. }
  50. /// The relative priority of this download task.
  51. /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task.
  52. /// The value for it is between 0.0~1.0. Default priority is value of 0.5.
  53. /// See documentation on `priority` of `NSURLSessionTask` for more about it.
  54. public var priority: Float {
  55. get {
  56. return internalTask.priority
  57. }
  58. set {
  59. internalTask.priority = newValue
  60. }
  61. }
  62. }
  63. private let defaultDownloaderName = "default"
  64. private let downloaderBarrierName = "com.onevcat.Kingfisher.ImageDownloader.Barrier."
  65. private let imageProcessQueueName = "com.onevcat.Kingfisher.ImageDownloader.Process."
  66. private let instance = ImageDownloader(name: defaultDownloaderName)
  67. /**
  68. The error code.
  69. - badData: The downloaded data is not an image or the data is corrupted.
  70. - notModified: The remote server responsed a 304 code. No image data downloaded.
  71. - invalidStatusCode: The HTTP status code in response is not valid.
  72. - notCached: The image rquested is not in cache but .onlyFromCache is activated.
  73. - invalidURL: The URL is invalid.
  74. */
  75. public enum KingfisherError: Int {
  76. case badData = 10000
  77. case notModified = 10001
  78. case invalidStatusCode = 10002
  79. case notCached = 10003
  80. case invalidURL = 20000
  81. }
  82. public let KingfisherErrorStatusCodeKey = "statusCode"
  83. /// Protocol of `ImageDownloader`.
  84. @objc public protocol ImageDownloaderDelegate {
  85. /**
  86. Called when the `ImageDownloader` object successfully downloaded an image from specified URL.
  87. - parameter downloader: The `ImageDownloader` object finishes the downloading.
  88. - parameter image: Downloaded image.
  89. - parameter URL: URL of the original request URL.
  90. - parameter response: The response object of the downloading process.
  91. */
  92. @objc optional func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?)
  93. /**
  94. Check if a received HTTP status code is valid or not.
  95. By default, a status code between 200 to 400 (not included) is considered as valid.
  96. If an invalid code is received, the downloader will raise an .invalidStatusCode error.
  97. It has a `userInfo` which includes this statusCode and localizedString error message.
  98. - parameter code: The received HTTP status code.
  99. - returns: Whether this HTTP status code is valid or not.
  100. - Note: If the default 200 to 400 valid code does not suit your need,
  101. you can implement this method to change that behavior.
  102. */
  103. @objc optional func isValidStatusCode(_ code: Int) -> Bool
  104. }
  105. /// Protocol indicates that an authentication challenge could be handled.
  106. public protocol AuthenticationChallengeResponable: class {
  107. /**
  108. Called when an session level authentication challenge is received.
  109. This method provide a chance to handle and response to the authentication challenge before downloading could start.
  110. - parameter downloader: The downloader which receives this challenge.
  111. - parameter challenge: An object that contains the request for authentication.
  112. - parameter completionHandler: A handler that your delegate method must call.
  113. - Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`.
  114. */
  115. func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  116. }
  117. extension AuthenticationChallengeResponable {
  118. func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  119. if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  120. if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) {
  121. let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
  122. completionHandler(.useCredential, credential)
  123. return
  124. }
  125. }
  126. completionHandler(.performDefaultHandling, nil)
  127. }
  128. }
  129. /// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server.
  130. public class ImageDownloader: NSObject {
  131. class ImageFetchLoad {
  132. var callbacks = [CallbackPair]()
  133. var responseData = NSMutableData()
  134. var options: KingfisherOptionsInfo?
  135. var downloadTaskCount = 0
  136. var downloadTask: RetrieveImageDownloadTask?
  137. }
  138. // MARK: - Public property
  139. /// This closure will be applied to the image download request before it being sent.
  140. /// You can modify the request for some customizing purpose, like adding auth token to the header, do basic HTTP auth or something like url mapping.
  141. public var requestModifier: ((inout URLRequest) -> Void)?
  142. /// The duration before the download is timeout. Default is 15 seconds.
  143. public var downloadTimeout: TimeInterval = 15.0
  144. /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored.
  145. /// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`.
  146. /// If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead.
  147. public var trustedHosts: Set<String>?
  148. /// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used.
  149. /// You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly.
  150. public var sessionConfiguration = URLSessionConfiguration.ephemeral {
  151. didSet {
  152. session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: OperationQueue.main)
  153. }
  154. }
  155. /// Whether the download requests should use pipeling or not. Default is false.
  156. public var requestsUsePipeling = false
  157. private let sessionHandler: ImageDownloaderSessionHandler
  158. private var session: URLSession?
  159. /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
  160. public weak var delegate: ImageDownloaderDelegate?
  161. /// A responder for authentication challenge.
  162. /// Downloader will forward the received authentication challenge for the downloading session to this responder.
  163. public weak var authenticationChallengeResponder: AuthenticationChallengeResponable?
  164. // MARK: - Internal property
  165. let barrierQueue: DispatchQueue
  166. let processQueue: DispatchQueue
  167. typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHander: ImageDownloaderCompletionHandler?)
  168. var fetchLoads = [URL: ImageFetchLoad]()
  169. // MARK: - Public method
  170. /// The default downloader.
  171. public class var `default`: ImageDownloader {
  172. return instance
  173. }
  174. /**
  175. Init a downloader with name.
  176. - parameter name: The name for the downloader. It should not be empty.
  177. - returns: The downloader object.
  178. */
  179. public init(name: String) {
  180. if name.isEmpty {
  181. fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.")
  182. }
  183. barrierQueue = DispatchQueue(label: downloaderBarrierName + name, attributes: .concurrent)
  184. processQueue = DispatchQueue(label: imageProcessQueueName + name, attributes: .concurrent)
  185. sessionHandler = ImageDownloaderSessionHandler()
  186. super.init()
  187. // Provide a default implement for challenge responder.
  188. authenticationChallengeResponder = sessionHandler
  189. session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main)
  190. }
  191. func fetchLoad(for url: URL) -> ImageFetchLoad? {
  192. var fetchLoad: ImageFetchLoad?
  193. barrierQueue.sync { fetchLoad = fetchLoads[url] }
  194. return fetchLoad
  195. }
  196. }
  197. // MARK: - Download method
  198. extension ImageDownloader {
  199. /**
  200. Download an image with a URL.
  201. - parameter url: Target URL.
  202. - parameter progressBlock: Called when the download progress updated.
  203. - parameter completionHandler: Called when the download progress finishes.
  204. - returns: A downloading task. You could call `cancel` on it to stop the downloading process.
  205. */
  206. @discardableResult
  207. public func downloadImage(with url: URL,
  208. progressBlock: ImageDownloaderProgressBlock?,
  209. completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
  210. {
  211. return downloadImage(with: url, options: nil, progressBlock: progressBlock, completionHandler: completionHandler)
  212. }
  213. /**
  214. Download an image with a URL and option.
  215. - parameter url: Target URL.
  216. - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`.
  217. - parameter progressBlock: Called when the download progress updated.
  218. - parameter completionHandler: Called when the download progress finishes.
  219. - returns: A downloading task. You could call `cancel` on it to stop the downloading process.
  220. */
  221. @discardableResult
  222. public func downloadImage(with url: URL,
  223. options: KingfisherOptionsInfo?,
  224. progressBlock: ImageDownloaderProgressBlock?,
  225. completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
  226. {
  227. return downloadImage(with: url,
  228. retrieveImageTask: nil,
  229. options: options,
  230. progressBlock: progressBlock,
  231. completionHandler: completionHandler)
  232. }
  233. func downloadImage(with url: URL,
  234. retrieveImageTask: RetrieveImageTask?,
  235. options: KingfisherOptionsInfo?,
  236. progressBlock: ImageDownloaderProgressBlock?,
  237. completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask?
  238. {
  239. if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting {
  240. return nil
  241. }
  242. let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout
  243. // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL.
  244. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout)
  245. request.httpShouldUsePipelining = requestsUsePipeling
  246. self.requestModifier?(&request)
  247. // There is a possiblility that request modifier changed the url to `nil` or empty.
  248. guard let url = request.url, !url.absoluteString.isEmpty else {
  249. completionHandler?(image: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), url: nil, originalData: nil)
  250. return nil
  251. }
  252. var downloadTask: RetrieveImageDownloadTask?
  253. setup(progressBlock: progressBlock, with: completionHandler, for: url) {(session, fetchLoad) -> Void in
  254. if fetchLoad.downloadTask == nil {
  255. let dataTask = session.dataTask(with: request)
  256. fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self)
  257. fetchLoad.options = options
  258. dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority
  259. dataTask.resume()
  260. // Hold self while the task is executing.
  261. sessionHandler.downloadHolder = self
  262. }
  263. fetchLoad.downloadTaskCount += 1
  264. downloadTask = fetchLoad.downloadTask
  265. retrieveImageTask?.downloadTask = downloadTask
  266. }
  267. return downloadTask
  268. }
  269. // A single key may have multiple callbacks. Only download once.
  270. func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, started: (@noescape (URLSession, ImageFetchLoad) -> Void)) {
  271. barrierQueue.sync(flags: .barrier) {
  272. let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad()
  273. let callbackPair = (progressBlock: progressBlock, completionHander: completionHandler)
  274. loadObjectForURL.callbacks.append(callbackPair)
  275. fetchLoads[url] = loadObjectForURL
  276. if let session = session {
  277. started(session, loadObjectForURL)
  278. }
  279. }
  280. }
  281. func cancelDownloadingTask(_ task: RetrieveImageDownloadTask) {
  282. barrierQueue.sync {
  283. if let URL = task.internalTask.originalRequest?.url, let imageFetchLoad = self.fetchLoads[URL] {
  284. imageFetchLoad.downloadTaskCount -= 1
  285. if imageFetchLoad.downloadTaskCount == 0 {
  286. task.internalTask.cancel()
  287. }
  288. }
  289. }
  290. }
  291. func clean(for url: URL) {
  292. barrierQueue.sync(flags: .barrier) {
  293. fetchLoads.removeValue(forKey: url)
  294. return
  295. }
  296. }
  297. }
  298. // MARK: - NSURLSessionDataDelegate
  299. /// Delegate class for `NSURLSessionTaskDelegate`.
  300. /// The session object will hold its delegate until it gets invalidated.
  301. /// If we use `ImageDownloader` as the session delegate, it will not be released.
  302. /// So we need an additional handler to break the retain cycle.
  303. // See https://github.com/onevcat/Kingfisher/issues/235
  304. class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponable {
  305. // The holder will keep downloader not released while a data task is being executed.
  306. // It will be set when the task started, and reset when the task finished.
  307. var downloadHolder: ImageDownloader?
  308. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) {
  309. if let statusCode = (response as? HTTPURLResponse)?.statusCode,
  310. let url = dataTask.originalRequest?.url, !isValidStatusCode(code: statusCode)
  311. {
  312. callback(with: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidStatusCode.rawValue, userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)]), url: url, originalData: nil)
  313. }
  314. completionHandler(.allow)
  315. }
  316. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  317. guard let downloader = downloadHolder else {
  318. return
  319. }
  320. if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) {
  321. fetchLoad.responseData.append(data)
  322. for callbackPair in fetchLoad.callbacks {
  323. DispatchQueue.main.async(execute: { () -> Void in
  324. callbackPair.progressBlock?(receivedSize: Int64(fetchLoad.responseData.length), totalSize: dataTask.response!.expectedContentLength)
  325. })
  326. }
  327. }
  328. }
  329. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  330. if let url = task.originalRequest?.url {
  331. if let error = error { // Error happened
  332. callback(with: nil, error: error, url: url, originalData: nil)
  333. } else { //Download finished without error
  334. processImage(for: task, url: url)
  335. }
  336. }
  337. }
  338. /**
  339. This method is exposed since the compiler requests. Do not call it.
  340. */
  341. internal func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
  342. guard let downloader = downloadHolder else {
  343. return
  344. }
  345. downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler)
  346. }
  347. private func callback(with image: Image?, error: NSError?, url: URL, originalData: Data?) {
  348. guard let downloader = downloadHolder else {
  349. return
  350. }
  351. if let callbackPairs = downloader.fetchLoad(for: url)?.callbacks {
  352. let options = downloader.fetchLoad(for: url)?.options ?? KingfisherEmptyOptionsInfo
  353. downloader.clean(for: url)
  354. for callbackPair in callbackPairs {
  355. options.callbackDispatchQueue.safeAsync {
  356. callbackPair.completionHander?(image: image, error: error, url: url, originalData: originalData)
  357. }
  358. }
  359. if downloader.fetchLoads.isEmpty {
  360. downloadHolder = nil
  361. }
  362. }
  363. }
  364. private func processImage(for task: URLSessionTask, url: URL) {
  365. guard let downloader = downloadHolder else {
  366. return
  367. }
  368. // We are on main queue when receiving this.
  369. downloader.processQueue.async {
  370. guard let fetchLoad = downloader.fetchLoad(for: url) else {
  371. self.callback(with: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil), url: url, originalData: nil)
  372. return
  373. }
  374. let options = fetchLoad.options ?? KingfisherEmptyOptionsInfo
  375. let data = fetchLoad.responseData as Data
  376. if let image = Image.kf_image(data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData) {
  377. downloader.delegate?.imageDownloader?(downloader, didDownload: image, for: url, with: task.response)
  378. if options.backgroundDecode {
  379. self.callback(with: image.kf_decoded(scale: options.scaleFactor), error: nil, url: url, originalData: data)
  380. } else {
  381. self.callback(with: image, error: nil, url: url, originalData: data)
  382. }
  383. } else {
  384. // If server response is 304 (Not Modified), inform the callback handler with NotModified error.
  385. // It should be handled to get an image from cache, which is response of a manager object.
  386. if let res = task.response as? HTTPURLResponse , res.statusCode == 304 {
  387. self.callback(with: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil), url: url, originalData: nil)
  388. return
  389. }
  390. self.callback(with: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil), url: url, originalData: nil)
  391. }
  392. }
  393. }
  394. private func isValidStatusCode(code: Int) -> Bool {
  395. let inDefaultValidRange = (200..<400).contains(code)
  396. if let delegate = downloadHolder?.delegate {
  397. return delegate.isValidStatusCode?(code) ?? inDefaultValidRange
  398. } else {
  399. return inDefaultValidRange
  400. }
  401. }
  402. }