SDWebImageDownloader.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /*
  2. * This file is part of the SDWebImage package.
  3. * (c) Olivier Poitrey <rs@dailymotion.com>
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. */
  8. #import "SDWebImageDownloader.h"
  9. #import "SDWebImageDownloaderOperation.h"
  10. #import <ImageIO/ImageIO.h>
  11. @implementation SDWebImageDownloadToken
  12. @end
  13. @interface SDWebImageDownloader () <NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
  14. @property (strong, nonatomic, nonnull) NSOperationQueue *downloadQueue;
  15. @property (weak, nonatomic, nullable) NSOperation *lastAddedOperation;
  16. @property (assign, nonatomic, nullable) Class operationClass;
  17. @property (strong, nonatomic, nonnull) NSMutableDictionary<NSURL *, SDWebImageDownloaderOperation *> *URLOperations;
  18. @property (strong, nonatomic, nullable) SDHTTPHeadersMutableDictionary *HTTPHeaders;
  19. // This queue is used to serialize the handling of the network responses of all the download operation in a single queue
  20. @property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t barrierQueue;
  21. // The session in which data tasks will run
  22. @property (strong, nonatomic) NSURLSession *session;
  23. @end
  24. @implementation SDWebImageDownloader
  25. + (void)initialize {
  26. // Bind SDNetworkActivityIndicator if available (download it here: http://github.com/rs/SDNetworkActivityIndicator )
  27. // To use it, just add #import "SDNetworkActivityIndicator.h" in addition to the SDWebImage import
  28. if (NSClassFromString(@"SDNetworkActivityIndicator")) {
  29. #pragma clang diagnostic push
  30. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  31. id activityIndicator = [NSClassFromString(@"SDNetworkActivityIndicator") performSelector:NSSelectorFromString(@"sharedActivityIndicator")];
  32. #pragma clang diagnostic pop
  33. // Remove observer in case it was previously added.
  34. [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStartNotification object:nil];
  35. [[NSNotificationCenter defaultCenter] removeObserver:activityIndicator name:SDWebImageDownloadStopNotification object:nil];
  36. [[NSNotificationCenter defaultCenter] addObserver:activityIndicator
  37. selector:NSSelectorFromString(@"startActivity")
  38. name:SDWebImageDownloadStartNotification object:nil];
  39. [[NSNotificationCenter defaultCenter] addObserver:activityIndicator
  40. selector:NSSelectorFromString(@"stopActivity")
  41. name:SDWebImageDownloadStopNotification object:nil];
  42. }
  43. }
  44. + (nonnull instancetype)sharedDownloader {
  45. static dispatch_once_t once;
  46. static id instance;
  47. dispatch_once(&once, ^{
  48. instance = [self new];
  49. });
  50. return instance;
  51. }
  52. - (nonnull instancetype)init {
  53. return [self initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  54. }
  55. - (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration {
  56. if ((self = [super init])) {
  57. _operationClass = [SDWebImageDownloaderOperation class];
  58. _shouldDecompressImages = YES;
  59. _executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
  60. _downloadQueue = [NSOperationQueue new];
  61. _downloadQueue.maxConcurrentOperationCount = 6;
  62. _downloadQueue.name = @"com.hackemist.SDWebImageDownloader";
  63. _URLOperations = [NSMutableDictionary new];
  64. #ifdef SD_WEBP
  65. _HTTPHeaders = [@{@"Accept": @"image/webp,image/*;q=0.8"} mutableCopy];
  66. #else
  67. _HTTPHeaders = [@{@"Accept": @"image/*;q=0.8"} mutableCopy];
  68. #endif
  69. _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
  70. _downloadTimeout = 15.0;
  71. sessionConfiguration.timeoutIntervalForRequest = _downloadTimeout;
  72. /**
  73. * Create the session for this task
  74. * We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate
  75. * method calls and completion handler calls.
  76. */
  77. self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration
  78. delegate:self
  79. delegateQueue:nil];
  80. }
  81. return self;
  82. }
  83. - (void)dealloc {
  84. [self.session invalidateAndCancel];
  85. self.session = nil;
  86. [self.downloadQueue cancelAllOperations];
  87. SDDispatchQueueRelease(_barrierQueue);
  88. }
  89. - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field {
  90. if (value) {
  91. self.HTTPHeaders[field] = value;
  92. }
  93. else {
  94. [self.HTTPHeaders removeObjectForKey:field];
  95. }
  96. }
  97. - (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field {
  98. return self.HTTPHeaders[field];
  99. }
  100. - (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads {
  101. _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads;
  102. }
  103. - (NSUInteger)currentDownloadCount {
  104. return _downloadQueue.operationCount;
  105. }
  106. - (NSInteger)maxConcurrentDownloads {
  107. return _downloadQueue.maxConcurrentOperationCount;
  108. }
  109. - (void)setOperationClass:(nullable Class)operationClass {
  110. if (operationClass && [operationClass isSubclassOfClass:[NSOperation class]] && [operationClass conformsToProtocol:@protocol(SDWebImageDownloaderOperationInterface)]) {
  111. _operationClass = operationClass;
  112. } else {
  113. _operationClass = [SDWebImageDownloaderOperation class];
  114. }
  115. }
  116. - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
  117. options:(SDWebImageDownloaderOptions)options
  118. progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
  119. completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock {
  120. __weak SDWebImageDownloader *wself = self;
  121. return [self addProgressCallback:progressBlock completedBlock:completedBlock forURL:url createCallback:^SDWebImageDownloaderOperation *{
  122. __strong __typeof (wself) sself = wself;
  123. NSTimeInterval timeoutInterval = sself.downloadTimeout;
  124. if (timeoutInterval == 0.0) {
  125. timeoutInterval = 15.0;
  126. }
  127. // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise
  128. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
  129. request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
  130. request.HTTPShouldUsePipelining = YES;
  131. if (sself.headersFilter) {
  132. request.allHTTPHeaderFields = sself.headersFilter(url, [sself.HTTPHeaders copy]);
  133. }
  134. else {
  135. request.allHTTPHeaderFields = sself.HTTPHeaders;
  136. }
  137. SDWebImageDownloaderOperation *operation = [[sself.operationClass alloc] initWithRequest:request inSession:sself.session options:options];
  138. operation.shouldDecompressImages = sself.shouldDecompressImages;
  139. if (sself.urlCredential) {
  140. operation.credential = sself.urlCredential;
  141. } else if (sself.username && sself.password) {
  142. operation.credential = [NSURLCredential credentialWithUser:sself.username password:sself.password persistence:NSURLCredentialPersistenceForSession];
  143. }
  144. if (options & SDWebImageDownloaderHighPriority) {
  145. operation.queuePriority = NSOperationQueuePriorityHigh;
  146. } else if (options & SDWebImageDownloaderLowPriority) {
  147. operation.queuePriority = NSOperationQueuePriorityLow;
  148. }
  149. [sself.downloadQueue addOperation:operation];
  150. if (sself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
  151. // Emulate LIFO execution order by systematically adding new operations as last operation's dependency
  152. [sself.lastAddedOperation addDependency:operation];
  153. sself.lastAddedOperation = operation;
  154. }
  155. return operation;
  156. }];
  157. }
  158. - (void)cancel:(nullable SDWebImageDownloadToken *)token {
  159. dispatch_barrier_async(self.barrierQueue, ^{
  160. SDWebImageDownloaderOperation *operation = self.URLOperations[token.url];
  161. BOOL canceled = [operation cancel:token.downloadOperationCancelToken];
  162. if (canceled) {
  163. [self.URLOperations removeObjectForKey:token.url];
  164. }
  165. });
  166. }
  167. - (nullable SDWebImageDownloadToken *)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock
  168. completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock
  169. forURL:(nullable NSURL *)url
  170. createCallback:(SDWebImageDownloaderOperation *(^)())createCallback {
  171. // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data.
  172. if (url == nil) {
  173. if (completedBlock != nil) {
  174. completedBlock(nil, nil, nil, NO);
  175. }
  176. return nil;
  177. }
  178. __block SDWebImageDownloadToken *token = nil;
  179. dispatch_barrier_sync(self.barrierQueue, ^{
  180. SDWebImageDownloaderOperation *operation = self.URLOperations[url];
  181. if (!operation) {
  182. operation = createCallback();
  183. self.URLOperations[url] = operation;
  184. __weak SDWebImageDownloaderOperation *woperation = operation;
  185. operation.completionBlock = ^{
  186. SDWebImageDownloaderOperation *soperation = woperation;
  187. if (!soperation) return;
  188. if (self.URLOperations[url] == soperation) {
  189. [self.URLOperations removeObjectForKey:url];
  190. };
  191. };
  192. }
  193. id downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock];
  194. token = [SDWebImageDownloadToken new];
  195. token.url = url;
  196. token.downloadOperationCancelToken = downloadOperationCancelToken;
  197. });
  198. return token;
  199. }
  200. - (void)setSuspended:(BOOL)suspended {
  201. (self.downloadQueue).suspended = suspended;
  202. }
  203. - (void)cancelAllDownloads {
  204. [self.downloadQueue cancelAllOperations];
  205. }
  206. #pragma mark Helper methods
  207. - (SDWebImageDownloaderOperation *)operationWithTask:(NSURLSessionTask *)task {
  208. SDWebImageDownloaderOperation *returnOperation = nil;
  209. for (SDWebImageDownloaderOperation *operation in self.downloadQueue.operations) {
  210. if (operation.dataTask.taskIdentifier == task.taskIdentifier) {
  211. returnOperation = operation;
  212. break;
  213. }
  214. }
  215. return returnOperation;
  216. }
  217. #pragma mark NSURLSessionDataDelegate
  218. - (void)URLSession:(NSURLSession *)session
  219. dataTask:(NSURLSessionDataTask *)dataTask
  220. didReceiveResponse:(NSURLResponse *)response
  221. completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
  222. // Identify the operation that runs this task and pass it the delegate method
  223. SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask];
  224. [dataOperation URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler];
  225. }
  226. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
  227. // Identify the operation that runs this task and pass it the delegate method
  228. SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask];
  229. [dataOperation URLSession:session dataTask:dataTask didReceiveData:data];
  230. }
  231. - (void)URLSession:(NSURLSession *)session
  232. dataTask:(NSURLSessionDataTask *)dataTask
  233. willCacheResponse:(NSCachedURLResponse *)proposedResponse
  234. completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler {
  235. // Identify the operation that runs this task and pass it the delegate method
  236. SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask];
  237. [dataOperation URLSession:session dataTask:dataTask willCacheResponse:proposedResponse completionHandler:completionHandler];
  238. }
  239. #pragma mark NSURLSessionTaskDelegate
  240. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
  241. // Identify the operation that runs this task and pass it the delegate method
  242. SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:task];
  243. [dataOperation URLSession:session task:task didCompleteWithError:error];
  244. }
  245. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler {
  246. completionHandler(request);
  247. }
  248. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
  249. // Identify the operation that runs this task and pass it the delegate method
  250. SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:task];
  251. [dataOperation URLSession:session task:task didReceiveChallenge:challenge completionHandler:completionHandler];
  252. }
  253. @end