SDWebImageManager.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 "SDWebImageManager.h"
  9. #import <objc/message.h>
  10. #import "NSImage+WebCache.h"
  11. @interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>
  12. @property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
  13. @property (copy, nonatomic, nullable) SDWebImageNoParamsBlock cancelBlock;
  14. @property (strong, nonatomic, nullable) NSOperation *cacheOperation;
  15. @end
  16. @interface SDWebImageManager ()
  17. @property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache;
  18. @property (strong, nonatomic, readwrite, nonnull) SDWebImageDownloader *imageDownloader;
  19. @property (strong, nonatomic, nonnull) NSMutableSet<NSURL *> *failedURLs;
  20. @property (strong, nonatomic, nonnull) NSMutableArray<SDWebImageCombinedOperation *> *runningOperations;
  21. @end
  22. @implementation SDWebImageManager
  23. + (nonnull instancetype)sharedManager {
  24. static dispatch_once_t once;
  25. static id instance;
  26. dispatch_once(&once, ^{
  27. instance = [self new];
  28. });
  29. return instance;
  30. }
  31. - (nonnull instancetype)init {
  32. SDImageCache *cache = [SDImageCache sharedImageCache];
  33. SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
  34. return [self initWithCache:cache downloader:downloader];
  35. }
  36. - (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader {
  37. if ((self = [super init])) {
  38. _imageCache = cache;
  39. _imageDownloader = downloader;
  40. _failedURLs = [NSMutableSet new];
  41. _runningOperations = [NSMutableArray new];
  42. }
  43. return self;
  44. }
  45. - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url {
  46. if (!url) {
  47. return @"";
  48. }
  49. if (self.cacheKeyFilter) {
  50. return self.cacheKeyFilter(url);
  51. } else {
  52. return url.absoluteString;
  53. }
  54. }
  55. - (void)cachedImageExistsForURL:(nullable NSURL *)url
  56. completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
  57. NSString *key = [self cacheKeyForURL:url];
  58. BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil);
  59. if (isInMemoryCache) {
  60. // making sure we call the completion block on the main queue
  61. dispatch_async(dispatch_get_main_queue(), ^{
  62. if (completionBlock) {
  63. completionBlock(YES);
  64. }
  65. });
  66. return;
  67. }
  68. [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
  69. // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
  70. if (completionBlock) {
  71. completionBlock(isInDiskCache);
  72. }
  73. }];
  74. }
  75. - (void)diskImageExistsForURL:(nullable NSURL *)url
  76. completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
  77. NSString *key = [self cacheKeyForURL:url];
  78. [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
  79. // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
  80. if (completionBlock) {
  81. completionBlock(isInDiskCache);
  82. }
  83. }];
  84. }
  85. - (id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
  86. options:(SDWebImageOptions)options
  87. progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
  88. completed:(nullable SDInternalCompletionBlock)completedBlock {
  89. // Invoking this method without a completedBlock is pointless
  90. NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead");
  91. // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, Xcode won't
  92. // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString.
  93. if ([url isKindOfClass:NSString.class]) {
  94. url = [NSURL URLWithString:(NSString *)url];
  95. }
  96. // Prevents app crashing on argument type error like sending NSNull instead of NSURL
  97. if (![url isKindOfClass:NSURL.class]) {
  98. url = nil;
  99. }
  100. __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
  101. __weak SDWebImageCombinedOperation *weakOperation = operation;
  102. BOOL isFailedUrl = NO;
  103. if (url) {
  104. @synchronized (self.failedURLs) {
  105. isFailedUrl = [self.failedURLs containsObject:url];
  106. }
  107. }
  108. if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
  109. [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil] url:url];
  110. return operation;
  111. }
  112. @synchronized (self.runningOperations) {
  113. [self.runningOperations addObject:operation];
  114. }
  115. NSString *key = [self cacheKeyForURL:url];
  116. operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) {
  117. if (operation.isCancelled) {
  118. [self safelyRemoveOperationFromRunning:operation];
  119. return;
  120. }
  121. if ((!cachedImage || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
  122. if (cachedImage && options & SDWebImageRefreshCached) {
  123. // If image was found in the cache but SDWebImageRefreshCached is provided, notify about the cached image
  124. // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server.
  125. [self callCompletionBlockForOperation:weakOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
  126. }
  127. // download if no image or requested to refresh anyway, and download allowed by delegate
  128. SDWebImageDownloaderOptions downloaderOptions = 0;
  129. if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority;
  130. if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload;
  131. if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache;
  132. if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground;
  133. if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies;
  134. if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates;
  135. if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority;
  136. if (options & SDWebImageScaleDownLargeImages) downloaderOptions |= SDWebImageDownloaderScaleDownLargeImages;
  137. if (cachedImage && options & SDWebImageRefreshCached) {
  138. // force progressive off if image already cached but forced refreshing
  139. downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload;
  140. // ignore image read from NSURLCache if image if cached but force refreshing
  141. downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
  142. }
  143. SDWebImageDownloadToken *subOperationToken = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) {
  144. __strong __typeof(weakOperation) strongOperation = weakOperation;
  145. if (!strongOperation || strongOperation.isCancelled) {
  146. // Do nothing if the operation was cancelled
  147. // See #699 for more details
  148. // if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data
  149. } else if (error) {
  150. [self callCompletionBlockForOperation:strongOperation completion:completedBlock error:error url:url];
  151. if ( error.code != NSURLErrorNotConnectedToInternet
  152. && error.code != NSURLErrorCancelled
  153. && error.code != NSURLErrorTimedOut
  154. && error.code != NSURLErrorInternationalRoamingOff
  155. && error.code != NSURLErrorDataNotAllowed
  156. && error.code != NSURLErrorCannotFindHost
  157. && error.code != NSURLErrorCannotConnectToHost
  158. && error.code != NSURLErrorNetworkConnectionLost) {
  159. @synchronized (self.failedURLs) {
  160. [self.failedURLs addObject:url];
  161. }
  162. }
  163. }
  164. else {
  165. if ((options & SDWebImageRetryFailed)) {
  166. @synchronized (self.failedURLs) {
  167. [self.failedURLs removeObject:url];
  168. }
  169. }
  170. BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);
  171. if (options & SDWebImageRefreshCached && cachedImage && !downloadedImage) {
  172. // Image refresh hit the NSURLCache cache, do not call the completion block
  173. } else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
  174. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  175. UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
  176. if (transformedImage && finished) {
  177. BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
  178. // pass nil if the image was transformed, so we can recalculate the data from the image
  179. [self.imageCache storeImage:transformedImage imageData:(imageWasTransformed ? nil : downloadedData) forKey:key toDisk:cacheOnDisk completion:nil];
  180. }
  181. [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:transformedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
  182. });
  183. } else {
  184. if (downloadedImage && finished) {
  185. [self.imageCache storeImage:downloadedImage imageData:downloadedData forKey:key toDisk:cacheOnDisk completion:nil];
  186. }
  187. [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:downloadedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
  188. }
  189. }
  190. if (finished) {
  191. [self safelyRemoveOperationFromRunning:strongOperation];
  192. }
  193. }];
  194. operation.cancelBlock = ^{
  195. [self.imageDownloader cancel:subOperationToken];
  196. __strong __typeof(weakOperation) strongOperation = weakOperation;
  197. [self safelyRemoveOperationFromRunning:strongOperation];
  198. };
  199. } else if (cachedImage) {
  200. __strong __typeof(weakOperation) strongOperation = weakOperation;
  201. [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
  202. [self safelyRemoveOperationFromRunning:operation];
  203. } else {
  204. // Image not in cache and download disallowed by delegate
  205. __strong __typeof(weakOperation) strongOperation = weakOperation;
  206. [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES url:url];
  207. [self safelyRemoveOperationFromRunning:operation];
  208. }
  209. }];
  210. return operation;
  211. }
  212. - (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url {
  213. if (image && url) {
  214. NSString *key = [self cacheKeyForURL:url];
  215. [self.imageCache storeImage:image forKey:key toDisk:YES completion:nil];
  216. }
  217. }
  218. - (void)cancelAll {
  219. @synchronized (self.runningOperations) {
  220. NSArray<SDWebImageCombinedOperation *> *copiedOperations = [self.runningOperations copy];
  221. [copiedOperations makeObjectsPerformSelector:@selector(cancel)];
  222. [self.runningOperations removeObjectsInArray:copiedOperations];
  223. }
  224. }
  225. - (BOOL)isRunning {
  226. BOOL isRunning = NO;
  227. @synchronized (self.runningOperations) {
  228. isRunning = (self.runningOperations.count > 0);
  229. }
  230. return isRunning;
  231. }
  232. - (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation {
  233. @synchronized (self.runningOperations) {
  234. if (operation) {
  235. [self.runningOperations removeObject:operation];
  236. }
  237. }
  238. }
  239. - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
  240. completion:(nullable SDInternalCompletionBlock)completionBlock
  241. error:(nullable NSError *)error
  242. url:(nullable NSURL *)url {
  243. [self callCompletionBlockForOperation:operation completion:completionBlock image:nil data:nil error:error cacheType:SDImageCacheTypeNone finished:YES url:url];
  244. }
  245. - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
  246. completion:(nullable SDInternalCompletionBlock)completionBlock
  247. image:(nullable UIImage *)image
  248. data:(nullable NSData *)data
  249. error:(nullable NSError *)error
  250. cacheType:(SDImageCacheType)cacheType
  251. finished:(BOOL)finished
  252. url:(nullable NSURL *)url {
  253. dispatch_main_async_safe(^{
  254. if (operation && !operation.isCancelled && completionBlock) {
  255. completionBlock(image, data, error, cacheType, finished, url);
  256. }
  257. });
  258. }
  259. @end
  260. @implementation SDWebImageCombinedOperation
  261. - (void)setCancelBlock:(nullable SDWebImageNoParamsBlock)cancelBlock {
  262. // check if the operation is already cancelled, then we just call the cancelBlock
  263. if (self.isCancelled) {
  264. if (cancelBlock) {
  265. cancelBlock();
  266. }
  267. _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes
  268. } else {
  269. _cancelBlock = [cancelBlock copy];
  270. }
  271. }
  272. - (void)cancel {
  273. self.cancelled = YES;
  274. if (self.cacheOperation) {
  275. [self.cacheOperation cancel];
  276. self.cacheOperation = nil;
  277. }
  278. if (self.cancelBlock) {
  279. self.cancelBlock();
  280. // TODO: this is a temporary fix to #809.
  281. // Until we can figure the exact cause of the crash, going with the ivar instead of the setter
  282. // self.cancelBlock = nil;
  283. _cancelBlock = nil;
  284. }
  285. }
  286. @end