SDWebImageManager.m 16 KB

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