EMSDWebImageManager.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 "EMSDWebImageManager.h"
  9. #import <objc/message.h>
  10. @interface EMSDWebImageCombinedOperation : NSObject <EMSDWebImageOperation>
  11. @property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
  12. @property (copy, nonatomic) EMSDWebImageNoParamsBlock cancelBlock;
  13. @property (strong, nonatomic) NSOperation *cacheOperation;
  14. @end
  15. @interface EMSDWebImageManager ()
  16. @property (strong, nonatomic, readwrite) EMSDImageCache *imageCache;
  17. @property (strong, nonatomic, readwrite) EMSDWebImageDownloader *imageDownloader;
  18. @property (strong, nonatomic) NSMutableArray *failedURLs;
  19. @property (strong, nonatomic) NSMutableArray *runningOperations;
  20. @end
  21. @implementation EMSDWebImageManager
  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 = [EMSDWebImageDownloader sharedDownloader];
  34. _failedURLs = [NSMutableArray new];
  35. _runningOperations = [NSMutableArray new];
  36. }
  37. return self;
  38. }
  39. - (EMSDImageCache *)createCache {
  40. return [EMSDImageCache 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:(EMSDWebImageCheckCacheCompletionBlock)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:(EMSDWebImageCheckCacheCompletionBlock)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 <EMSDWebImageOperation>)downloadImageWithURL:(NSURL *)url
  90. options:(EMSDWebImageOptions)options
  91. progress:(EMSDWebImageDownloaderProgressBlock)progressBlock
  92. completed:(EMSDWebImageCompletionWithFinishedBlock)completedBlock {
  93. // Invoking this method without a completedBlock is pointless
  94. NSParameterAssert(completedBlock);
  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 EMSDWebImageCombinedOperation *operation = [EMSDWebImageCombinedOperation new];
  105. __weak EMSDWebImageCombinedOperation *weakOperation = operation;
  106. BOOL isFailedUrl = NO;
  107. @synchronized (self.failedURLs) {
  108. isFailedUrl = [self.failedURLs containsObject:url];
  109. }
  110. if (!url || (!(options & EMSDWebImageRetryFailed) && isFailedUrl)) {
  111. dispatch_main_sync_safe(^{
  112. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil];
  113. completedBlock(nil, error, EMSDImageCacheTypeNone, 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, EMSDImageCacheType cacheType) {
  122. if (operation.isCancelled) {
  123. @synchronized (self.runningOperations) {
  124. [self.runningOperations removeObject:operation];
  125. }
  126. return;
  127. }
  128. if ((!image || options & EMSDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
  129. if (image && options & EMSDWebImageRefreshCached) {
  130. dispatch_main_sync_safe(^{
  131. // If image was found in the cache bug EMSDWebImageRefreshCached 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. EMSDWebImageDownloaderOptions downloaderOptions = 0;
  138. if (options & EMSDWebImageLowPriority) downloaderOptions |= EMSDWebImageDownloaderLowPriority;
  139. if (options & EMSDWebImageProgressiveDownload) downloaderOptions |= EMSDWebImageDownloaderProgressiveDownload;
  140. if (options & EMSDWebImageRefreshCached) downloaderOptions |= EMSDWebImageDownloaderUseNSURLCache;
  141. if (options & EMSDWebImageContinueInBackground) downloaderOptions |= EMSDWebImageDownloaderContinueInBackground;
  142. if (options & EMSDWebImageHandleCookies) downloaderOptions |= EMSDWebImageDownloaderHandleCookies;
  143. if (options & EMSDWebImageAllowInvalidSSLCertificates) downloaderOptions |= EMSDWebImageDownloaderAllowInvalidSSLCertificates;
  144. if (options & EMSDWebImageHighPriority) downloaderOptions |= EMSDWebImageDownloaderHighPriority;
  145. if (image && options & EMSDWebImageRefreshCached) {
  146. // force progressive off if image already cached but forced refreshing
  147. downloaderOptions &= ~EMSDWebImageDownloaderProgressiveDownload;
  148. // ignore image read from NSURLCache if image if cached but force refreshing
  149. downloaderOptions |= EMSDWebImageDownloaderIgnoreCachedResponse;
  150. }
  151. id <EMSDWebImageOperation> 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, EMSDImageCacheTypeNone, finished, url);
  161. }
  162. });
  163. if (error.code != NSURLErrorNotConnectedToInternet && error.code != NSURLErrorCancelled && error.code != NSURLErrorTimedOut) {
  164. @synchronized (self.failedURLs) {
  165. [self.failedURLs addObject:url];
  166. }
  167. }
  168. }
  169. else {
  170. BOOL cacheOnDisk = !(options & EMSDWebImageCacheMemoryOnly);
  171. if (options & EMSDWebImageRefreshCached && image && !downloadedImage) {
  172. // Image refresh hit the NSURLCache cache, do not call the completion block
  173. }
  174. // NOTE: We don't call transformDownloadedImage delegate method on animated images as most transformation code would mangle it
  175. else if (downloadedImage && !downloadedImage.images && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
  176. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  177. UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
  178. if (transformedImage && finished) {
  179. BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
  180. [self.imageCache storeImage:transformedImage recalculateFromImage:imageWasTransformed imageData:data forKey:key toDisk:cacheOnDisk];
  181. }
  182. dispatch_main_sync_safe(^{
  183. if (!weakOperation.isCancelled) {
  184. completedBlock(transformedImage, nil, EMSDImageCacheTypeNone, finished, url);
  185. }
  186. });
  187. });
  188. }
  189. else {
  190. if (downloadedImage && finished) {
  191. [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk];
  192. }
  193. dispatch_main_sync_safe(^{
  194. if (!weakOperation.isCancelled) {
  195. completedBlock(downloadedImage, nil, EMSDImageCacheTypeNone, finished, url);
  196. }
  197. });
  198. }
  199. }
  200. if (finished) {
  201. @synchronized (self.runningOperations) {
  202. [self.runningOperations removeObject:operation];
  203. }
  204. }
  205. }];
  206. operation.cancelBlock = ^{
  207. [subOperation cancel];
  208. @synchronized (self.runningOperations) {
  209. [self.runningOperations removeObject:weakOperation];
  210. }
  211. };
  212. }
  213. else if (image) {
  214. dispatch_main_sync_safe(^{
  215. if (!weakOperation.isCancelled) {
  216. completedBlock(image, nil, cacheType, YES, url);
  217. }
  218. });
  219. @synchronized (self.runningOperations) {
  220. [self.runningOperations removeObject:operation];
  221. }
  222. }
  223. else {
  224. // Image not in cache and download disallowed by delegate
  225. dispatch_main_sync_safe(^{
  226. if (!weakOperation.isCancelled) {
  227. completedBlock(nil, nil, EMSDImageCacheTypeNone, YES, url);
  228. }
  229. });
  230. @synchronized (self.runningOperations) {
  231. [self.runningOperations removeObject:operation];
  232. }
  233. }
  234. }];
  235. return operation;
  236. }
  237. - (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url {
  238. if (image && url) {
  239. NSString *key = [self cacheKeyForURL:url];
  240. [self.imageCache storeImage:image forKey:key toDisk:YES];
  241. }
  242. }
  243. - (void)cancelAll {
  244. @synchronized (self.runningOperations) {
  245. [self.runningOperations makeObjectsPerformSelector:@selector(cancel)];
  246. [self.runningOperations removeAllObjects];
  247. }
  248. }
  249. - (BOOL)isRunning {
  250. return self.runningOperations.count > 0;
  251. }
  252. @end
  253. @implementation EMSDWebImageCombinedOperation
  254. - (void)setCancelBlock:(EMSDWebImageNoParamsBlock)cancelBlock {
  255. // check if the operation is already cancelled, then we just call the cancelBlock
  256. if (self.isCancelled) {
  257. if (cancelBlock) {
  258. cancelBlock();
  259. }
  260. _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes
  261. } else {
  262. _cancelBlock = [cancelBlock copy];
  263. }
  264. }
  265. - (void)cancel {
  266. self.cancelled = YES;
  267. if (self.cacheOperation) {
  268. [self.cacheOperation cancel];
  269. self.cacheOperation = nil;
  270. }
  271. if (self.cancelBlock) {
  272. self.cancelBlock();
  273. // TODO: this is a temporary fix to #809.
  274. // Until we can figure the exact cause of the crash, going with the ivar instead of the setter
  275. // self.cancelBlock = nil;
  276. _cancelBlock = nil;
  277. }
  278. }
  279. @end
  280. @implementation EMSDWebImageManager (Deprecated)
  281. // deprecated method, uses the non deprecated method
  282. // adapter for the completion block
  283. - (id <EMSDWebImageOperation>)downloadWithURL:(NSURL *)url options:(EMSDWebImageOptions)options progress:(EMSDWebImageDownloaderProgressBlock)progressBlock completed:(EMSDWebImageCompletedWithFinishedBlock)completedBlock {
  284. return [self downloadImageWithURL:url
  285. options:options
  286. progress:progressBlock
  287. completed:^(UIImage *image, NSError *error, EMSDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
  288. if (completedBlock) {
  289. completedBlock(image, error, cacheType, finished);
  290. }
  291. }];
  292. }
  293. @end