SDWebImageManager.m 14 KB

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