SDWebImageDownloader.m 14 KB

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