SDWebImageManager.m 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  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 "SDImageCache.h"
  10. #import "SDWebImageDownloader.h"
  11. #import "UIImage+Metadata.h"
  12. #import "SDAssociatedObject.h"
  13. #import "SDWebImageError.h"
  14. #import "SDInternalMacros.h"
  15. #import "SDCallbackQueue.h"
  16. static id<SDImageCache> _defaultImageCache;
  17. static id<SDImageLoader> _defaultImageLoader;
  18. @interface SDWebImageCombinedOperation ()
  19. @property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
  20. @property (strong, nonatomic, readwrite, nullable) id<SDWebImageOperation> loaderOperation;
  21. @property (strong, nonatomic, readwrite, nullable) id<SDWebImageOperation> cacheOperation;
  22. @property (weak, nonatomic, nullable) SDWebImageManager *manager;
  23. @end
  24. @interface SDWebImageManager () {
  25. SD_LOCK_DECLARE(_failedURLsLock); // a lock to keep the access to `failedURLs` thread-safe
  26. SD_LOCK_DECLARE(_runningOperationsLock); // a lock to keep the access to `runningOperations` thread-safe
  27. }
  28. @property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache;
  29. @property (strong, nonatomic, readwrite, nonnull) id<SDImageLoader> imageLoader;
  30. @property (strong, nonatomic, nonnull) NSMutableSet<NSURL *> *failedURLs;
  31. @property (strong, nonatomic, nonnull) NSMutableSet<SDWebImageCombinedOperation *> *runningOperations;
  32. @end
  33. @implementation SDWebImageManager
  34. + (id<SDImageCache>)defaultImageCache {
  35. return _defaultImageCache;
  36. }
  37. + (void)setDefaultImageCache:(id<SDImageCache>)defaultImageCache {
  38. if (defaultImageCache && ![defaultImageCache conformsToProtocol:@protocol(SDImageCache)]) {
  39. return;
  40. }
  41. _defaultImageCache = defaultImageCache;
  42. }
  43. + (id<SDImageLoader>)defaultImageLoader {
  44. return _defaultImageLoader;
  45. }
  46. + (void)setDefaultImageLoader:(id<SDImageLoader>)defaultImageLoader {
  47. if (defaultImageLoader && ![defaultImageLoader conformsToProtocol:@protocol(SDImageLoader)]) {
  48. return;
  49. }
  50. _defaultImageLoader = defaultImageLoader;
  51. }
  52. + (nonnull instancetype)sharedManager {
  53. static dispatch_once_t once;
  54. static id instance;
  55. dispatch_once(&once, ^{
  56. instance = [self new];
  57. });
  58. return instance;
  59. }
  60. - (nonnull instancetype)init {
  61. id<SDImageCache> cache = [[self class] defaultImageCache];
  62. if (!cache) {
  63. cache = [SDImageCache sharedImageCache];
  64. }
  65. id<SDImageLoader> loader = [[self class] defaultImageLoader];
  66. if (!loader) {
  67. loader = [SDWebImageDownloader sharedDownloader];
  68. }
  69. return [self initWithCache:cache loader:loader];
  70. }
  71. - (nonnull instancetype)initWithCache:(nonnull id<SDImageCache>)cache loader:(nonnull id<SDImageLoader>)loader {
  72. if ((self = [super init])) {
  73. _imageCache = cache;
  74. _imageLoader = loader;
  75. _failedURLs = [NSMutableSet new];
  76. SD_LOCK_INIT(_failedURLsLock);
  77. _runningOperations = [NSMutableSet new];
  78. SD_LOCK_INIT(_runningOperationsLock);
  79. }
  80. return self;
  81. }
  82. - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url {
  83. if (!url) {
  84. return @"";
  85. }
  86. NSString *key;
  87. // Cache Key Filter
  88. id<SDWebImageCacheKeyFilter> cacheKeyFilter = self.cacheKeyFilter;
  89. if (cacheKeyFilter) {
  90. key = [cacheKeyFilter cacheKeyForURL:url];
  91. } else {
  92. key = url.absoluteString;
  93. }
  94. return key;
  95. }
  96. - (nullable NSString *)originalCacheKeyForURL:(nullable NSURL *)url context:(nullable SDWebImageContext *)context {
  97. if (!url) {
  98. return @"";
  99. }
  100. NSString *key;
  101. // Cache Key Filter
  102. id<SDWebImageCacheKeyFilter> cacheKeyFilter = self.cacheKeyFilter;
  103. if (context[SDWebImageContextCacheKeyFilter]) {
  104. cacheKeyFilter = context[SDWebImageContextCacheKeyFilter];
  105. }
  106. if (cacheKeyFilter) {
  107. key = [cacheKeyFilter cacheKeyForURL:url];
  108. } else {
  109. key = url.absoluteString;
  110. }
  111. return key;
  112. }
  113. - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url context:(nullable SDWebImageContext *)context {
  114. if (!url) {
  115. return @"";
  116. }
  117. NSString *key;
  118. // Cache Key Filter
  119. id<SDWebImageCacheKeyFilter> cacheKeyFilter = self.cacheKeyFilter;
  120. if (context[SDWebImageContextCacheKeyFilter]) {
  121. cacheKeyFilter = context[SDWebImageContextCacheKeyFilter];
  122. }
  123. if (cacheKeyFilter) {
  124. key = [cacheKeyFilter cacheKeyForURL:url];
  125. } else {
  126. key = url.absoluteString;
  127. }
  128. // Thumbnail Key Appending
  129. NSValue *thumbnailSizeValue = context[SDWebImageContextImageThumbnailPixelSize];
  130. if (thumbnailSizeValue != nil) {
  131. CGSize thumbnailSize = CGSizeZero;
  132. #if SD_MAC
  133. thumbnailSize = thumbnailSizeValue.sizeValue;
  134. #else
  135. thumbnailSize = thumbnailSizeValue.CGSizeValue;
  136. #endif
  137. BOOL preserveAspectRatio = YES;
  138. NSNumber *preserveAspectRatioValue = context[SDWebImageContextImagePreserveAspectRatio];
  139. if (preserveAspectRatioValue != nil) {
  140. preserveAspectRatio = preserveAspectRatioValue.boolValue;
  141. }
  142. key = SDThumbnailedKeyForKey(key, thumbnailSize, preserveAspectRatio);
  143. }
  144. // Transformer Key Appending
  145. id<SDImageTransformer> transformer = self.transformer;
  146. if (context[SDWebImageContextImageTransformer]) {
  147. transformer = context[SDWebImageContextImageTransformer];
  148. if ([transformer isEqual:NSNull.null]) {
  149. transformer = nil;
  150. }
  151. }
  152. if (transformer) {
  153. key = SDTransformedKeyForKey(key, transformer.transformerKey);
  154. }
  155. return key;
  156. }
  157. - (SDWebImageCombinedOperation *)loadImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDInternalCompletionBlock)completedBlock {
  158. return [self loadImageWithURL:url options:options context:nil progress:progressBlock completed:completedBlock];
  159. }
  160. - (SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url
  161. options:(SDWebImageOptions)options
  162. context:(nullable SDWebImageContext *)context
  163. progress:(nullable SDImageLoaderProgressBlock)progressBlock
  164. completed:(nonnull SDInternalCompletionBlock)completedBlock {
  165. // Invoking this method without a completedBlock is pointless
  166. NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead");
  167. // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, Xcode won't
  168. // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString.
  169. if ([url isKindOfClass:NSString.class]) {
  170. url = [NSURL URLWithString:(NSString *)url];
  171. }
  172. // Prevents app crashing on argument type error like sending NSNull instead of NSURL
  173. if (![url isKindOfClass:NSURL.class]) {
  174. url = nil;
  175. }
  176. SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
  177. operation.manager = self;
  178. BOOL isFailedUrl = NO;
  179. if (url) {
  180. SD_LOCK(_failedURLsLock);
  181. isFailedUrl = [self.failedURLs containsObject:url];
  182. SD_UNLOCK(_failedURLsLock);
  183. }
  184. // Preprocess the options and context arg to decide the final the result for manager
  185. SDWebImageOptionsResult *result = [self processedResultForURL:url options:options context:context];
  186. if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
  187. NSString *description = isFailedUrl ? @"Image url is blacklisted" : @"Image url is nil";
  188. NSInteger code = isFailedUrl ? SDWebImageErrorBlackListed : SDWebImageErrorInvalidURL;
  189. [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey : description}] queue:result.context[SDWebImageContextCallbackQueue] url:url];
  190. return operation;
  191. }
  192. SD_LOCK(_runningOperationsLock);
  193. [self.runningOperations addObject:operation];
  194. SD_UNLOCK(_runningOperationsLock);
  195. // Start the entry to load image from cache, the longest steps are below
  196. // Steps without transformer:
  197. // 1. query image from cache, miss
  198. // 2. download data and image
  199. // 3. store image to cache
  200. // Steps with transformer:
  201. // 1. query transformed image from cache, miss
  202. // 2. query original image from cache, miss
  203. // 3. download data and image
  204. // 4. do transform in CPU
  205. // 5. store original image to cache
  206. // 6. store transformed image to cache
  207. [self callCacheProcessForOperation:operation url:url options:result.options context:result.context progress:progressBlock completed:completedBlock];
  208. return operation;
  209. }
  210. - (void)cancelAll {
  211. SD_LOCK(_runningOperationsLock);
  212. NSSet<SDWebImageCombinedOperation *> *copiedOperations = [self.runningOperations copy];
  213. SD_UNLOCK(_runningOperationsLock);
  214. [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; // This will call `safelyRemoveOperationFromRunning:` and remove from the array
  215. }
  216. - (BOOL)isRunning {
  217. BOOL isRunning = NO;
  218. SD_LOCK(_runningOperationsLock);
  219. isRunning = (self.runningOperations.count > 0);
  220. SD_UNLOCK(_runningOperationsLock);
  221. return isRunning;
  222. }
  223. - (void)removeFailedURL:(NSURL *)url {
  224. if (!url) {
  225. return;
  226. }
  227. SD_LOCK(_failedURLsLock);
  228. [self.failedURLs removeObject:url];
  229. SD_UNLOCK(_failedURLsLock);
  230. }
  231. - (void)removeAllFailedURLs {
  232. SD_LOCK(_failedURLsLock);
  233. [self.failedURLs removeAllObjects];
  234. SD_UNLOCK(_failedURLsLock);
  235. }
  236. #pragma mark - Private
  237. // Query normal cache process
  238. - (void)callCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  239. url:(nonnull NSURL *)url
  240. options:(SDWebImageOptions)options
  241. context:(nullable SDWebImageContext *)context
  242. progress:(nullable SDImageLoaderProgressBlock)progressBlock
  243. completed:(nullable SDInternalCompletionBlock)completedBlock {
  244. // Grab the image cache to use
  245. id<SDImageCache> imageCache = context[SDWebImageContextImageCache];
  246. if (!imageCache) {
  247. imageCache = self.imageCache;
  248. }
  249. // Get the query cache type
  250. SDImageCacheType queryCacheType = SDImageCacheTypeAll;
  251. if (context[SDWebImageContextQueryCacheType]) {
  252. queryCacheType = [context[SDWebImageContextQueryCacheType] integerValue];
  253. }
  254. // Check whether we should query cache
  255. BOOL shouldQueryCache = !SD_OPTIONS_CONTAINS(options, SDWebImageFromLoaderOnly);
  256. if (shouldQueryCache) {
  257. // transformed cache key
  258. NSString *key = [self cacheKeyForURL:url context:context];
  259. @weakify(operation);
  260. operation.cacheOperation = [imageCache queryImageForKey:key options:options context:context cacheType:queryCacheType completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) {
  261. @strongify(operation);
  262. if (!operation || operation.isCancelled) {
  263. // Image combined operation cancelled by user
  264. [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during querying the cache"}] queue:context[SDWebImageContextCallbackQueue] url:url];
  265. [self safelyRemoveOperationFromRunning:operation];
  266. return;
  267. } else if (!cachedImage) {
  268. NSString *originKey = [self originalCacheKeyForURL:url context:context];
  269. BOOL mayInOriginalCache = ![key isEqualToString:originKey];
  270. // Have a chance to query original cache instead of downloading, then applying transform
  271. // Thumbnail decoding is done inside SDImageCache's decoding part, which does not need post processing for transform
  272. if (mayInOriginalCache) {
  273. [self callOriginalCacheProcessForOperation:operation url:url options:options context:context progress:progressBlock completed:completedBlock];
  274. return;
  275. }
  276. }
  277. // Continue download process
  278. [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:cachedImage cachedData:cachedData cacheType:cacheType progress:progressBlock completed:completedBlock];
  279. }];
  280. } else {
  281. // Continue download process
  282. [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock];
  283. }
  284. }
  285. // Query original cache process
  286. - (void)callOriginalCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  287. url:(nonnull NSURL *)url
  288. options:(SDWebImageOptions)options
  289. context:(nullable SDWebImageContext *)context
  290. progress:(nullable SDImageLoaderProgressBlock)progressBlock
  291. completed:(nullable SDInternalCompletionBlock)completedBlock {
  292. // Grab the image cache to use, choose standalone original cache firstly
  293. id<SDImageCache> imageCache = context[SDWebImageContextOriginalImageCache];
  294. if (!imageCache) {
  295. // if no standalone cache available, use default cache
  296. imageCache = context[SDWebImageContextImageCache];
  297. if (!imageCache) {
  298. imageCache = self.imageCache;
  299. }
  300. }
  301. // Get the original query cache type
  302. SDImageCacheType originalQueryCacheType = SDImageCacheTypeDisk;
  303. if (context[SDWebImageContextOriginalQueryCacheType]) {
  304. originalQueryCacheType = [context[SDWebImageContextOriginalQueryCacheType] integerValue];
  305. }
  306. // Check whether we should query original cache
  307. BOOL shouldQueryOriginalCache = (originalQueryCacheType != SDImageCacheTypeNone);
  308. if (shouldQueryOriginalCache) {
  309. // Get original cache key generation without transformer
  310. NSString *key = [self originalCacheKeyForURL:url context:context];
  311. @weakify(operation);
  312. operation.cacheOperation = [imageCache queryImageForKey:key options:options context:context cacheType:originalQueryCacheType completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) {
  313. @strongify(operation);
  314. if (!operation || operation.isCancelled) {
  315. // Image combined operation cancelled by user
  316. [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during querying the cache"}] queue:context[SDWebImageContextCallbackQueue] url:url];
  317. [self safelyRemoveOperationFromRunning:operation];
  318. return;
  319. } else if (!cachedImage) {
  320. // Original image cache miss. Continue download process
  321. [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock];
  322. return;
  323. }
  324. // Skip downloading and continue transform process, and ignore .refreshCached option for now
  325. [self callTransformProcessForOperation:operation url:url options:options context:context originalImage:cachedImage originalData:cachedData cacheType:cacheType finished:YES completed:completedBlock];
  326. [self safelyRemoveOperationFromRunning:operation];
  327. }];
  328. } else {
  329. // Continue download process
  330. [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock];
  331. }
  332. }
  333. // Download process
  334. - (void)callDownloadProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  335. url:(nonnull NSURL *)url
  336. options:(SDWebImageOptions)options
  337. context:(SDWebImageContext *)context
  338. cachedImage:(nullable UIImage *)cachedImage
  339. cachedData:(nullable NSData *)cachedData
  340. cacheType:(SDImageCacheType)cacheType
  341. progress:(nullable SDImageLoaderProgressBlock)progressBlock
  342. completed:(nullable SDInternalCompletionBlock)completedBlock {
  343. // Mark the cache operation end
  344. @synchronized (operation) {
  345. operation.cacheOperation = nil;
  346. }
  347. // Grab the image loader to use
  348. id<SDImageLoader> imageLoader = context[SDWebImageContextImageLoader];
  349. if (!imageLoader) {
  350. imageLoader = self.imageLoader;
  351. }
  352. // Check whether we should download image from network
  353. BOOL shouldDownload = !SD_OPTIONS_CONTAINS(options, SDWebImageFromCacheOnly);
  354. shouldDownload &= (!cachedImage || options & SDWebImageRefreshCached);
  355. shouldDownload &= (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url]);
  356. if ([imageLoader respondsToSelector:@selector(canRequestImageForURL:options:context:)]) {
  357. shouldDownload &= [imageLoader canRequestImageForURL:url options:options context:context];
  358. } else {
  359. shouldDownload &= [imageLoader canRequestImageForURL:url];
  360. }
  361. if (shouldDownload) {
  362. if (cachedImage && options & SDWebImageRefreshCached) {
  363. // If image was found in the cache but SDWebImageRefreshCached is provided, notify about the cached image
  364. // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server.
  365. [self callCompletionBlockForOperation:operation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES queue:context[SDWebImageContextCallbackQueue] url:url];
  366. // Pass the cached image to the image loader. The image loader should check whether the remote image is equal to the cached image.
  367. SDWebImageMutableContext *mutableContext;
  368. if (context) {
  369. mutableContext = [context mutableCopy];
  370. } else {
  371. mutableContext = [NSMutableDictionary dictionary];
  372. }
  373. mutableContext[SDWebImageContextLoaderCachedImage] = cachedImage;
  374. context = [mutableContext copy];
  375. }
  376. @weakify(operation);
  377. operation.loaderOperation = [imageLoader requestImageWithURL:url options:options context:context progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) {
  378. @strongify(operation);
  379. if (!operation || operation.isCancelled) {
  380. // Image combined operation cancelled by user
  381. [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during sending the request"}] queue:context[SDWebImageContextCallbackQueue] url:url];
  382. } else if (cachedImage && options & SDWebImageRefreshCached && [error.domain isEqualToString:SDWebImageErrorDomain] && error.code == SDWebImageErrorCacheNotModified) {
  383. // Image refresh hit the NSURLCache cache, do not call the completion block
  384. } else if ([error.domain isEqualToString:SDWebImageErrorDomain] && error.code == SDWebImageErrorCancelled) {
  385. // Download operation cancelled by user before sending the request, don't block failed URL
  386. [self callCompletionBlockForOperation:operation completion:completedBlock error:error queue:context[SDWebImageContextCallbackQueue] url:url];
  387. } else if (error) {
  388. [self callCompletionBlockForOperation:operation completion:completedBlock error:error queue:context[SDWebImageContextCallbackQueue] url:url];
  389. BOOL shouldBlockFailedURL = [self shouldBlockFailedURLWithURL:url error:error options:options context:context];
  390. if (shouldBlockFailedURL) {
  391. SD_LOCK(self->_failedURLsLock);
  392. [self.failedURLs addObject:url];
  393. SD_UNLOCK(self->_failedURLsLock);
  394. }
  395. } else {
  396. if ((options & SDWebImageRetryFailed)) {
  397. SD_LOCK(self->_failedURLsLock);
  398. [self.failedURLs removeObject:url];
  399. SD_UNLOCK(self->_failedURLsLock);
  400. }
  401. // Continue transform process
  402. [self callTransformProcessForOperation:operation url:url options:options context:context originalImage:downloadedImage originalData:downloadedData cacheType:SDImageCacheTypeNone finished:finished completed:completedBlock];
  403. }
  404. if (finished) {
  405. [self safelyRemoveOperationFromRunning:operation];
  406. }
  407. }];
  408. } else if (cachedImage) {
  409. [self callCompletionBlockForOperation:operation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES queue:context[SDWebImageContextCallbackQueue] url:url];
  410. [self safelyRemoveOperationFromRunning:operation];
  411. } else {
  412. // Image not in cache and download disallowed by delegate
  413. [self callCompletionBlockForOperation:operation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES queue:context[SDWebImageContextCallbackQueue] url:url];
  414. [self safelyRemoveOperationFromRunning:operation];
  415. }
  416. }
  417. // Transform process
  418. - (void)callTransformProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  419. url:(nonnull NSURL *)url
  420. options:(SDWebImageOptions)options
  421. context:(SDWebImageContext *)context
  422. originalImage:(nullable UIImage *)originalImage
  423. originalData:(nullable NSData *)originalData
  424. cacheType:(SDImageCacheType)cacheType
  425. finished:(BOOL)finished
  426. completed:(nullable SDInternalCompletionBlock)completedBlock {
  427. id<SDImageTransformer> transformer = context[SDWebImageContextImageTransformer];
  428. if ([transformer isEqual:NSNull.null]) {
  429. transformer = nil;
  430. }
  431. // transformer check
  432. BOOL shouldTransformImage = originalImage && transformer;
  433. shouldTransformImage = shouldTransformImage && (!originalImage.sd_isAnimated || (options & SDWebImageTransformAnimatedImage));
  434. shouldTransformImage = shouldTransformImage && (!originalImage.sd_isVector || (options & SDWebImageTransformVectorImage));
  435. // thumbnail check
  436. BOOL isThumbnail = originalImage.sd_isThumbnail;
  437. NSData *cacheData = originalData;
  438. UIImage *cacheImage = originalImage;
  439. if (isThumbnail) {
  440. cacheData = nil; // thumbnail don't store full size data
  441. originalImage = nil; // thumbnail don't have full size image
  442. }
  443. if (shouldTransformImage) {
  444. // transformed cache key
  445. NSString *key = [self cacheKeyForURL:url context:context];
  446. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  447. // Case that transformer on thumbnail, which this time need full pixel image
  448. UIImage *transformedImage = [transformer transformedImageWithImage:cacheImage forKey:key];
  449. if (transformedImage) {
  450. transformedImage.sd_isTransformed = YES;
  451. [self callStoreOriginCacheProcessForOperation:operation url:url options:options context:context originalImage:originalImage cacheImage:transformedImage originalData:originalData cacheData:nil cacheType:cacheType finished:finished completed:completedBlock];
  452. } else {
  453. [self callStoreOriginCacheProcessForOperation:operation url:url options:options context:context originalImage:originalImage cacheImage:cacheImage originalData:originalData cacheData:cacheData cacheType:cacheType finished:finished completed:completedBlock];
  454. }
  455. });
  456. } else {
  457. [self callStoreOriginCacheProcessForOperation:operation url:url options:options context:context originalImage:originalImage cacheImage:cacheImage originalData:originalData cacheData:cacheData cacheType:cacheType finished:finished completed:completedBlock];
  458. }
  459. }
  460. // Store origin cache process
  461. - (void)callStoreOriginCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  462. url:(nonnull NSURL *)url
  463. options:(SDWebImageOptions)options
  464. context:(SDWebImageContext *)context
  465. originalImage:(nullable UIImage *)originalImage
  466. cacheImage:(nullable UIImage *)cacheImage
  467. originalData:(nullable NSData *)originalData
  468. cacheData:(nullable NSData *)cacheData
  469. cacheType:(SDImageCacheType)cacheType
  470. finished:(BOOL)finished
  471. completed:(nullable SDInternalCompletionBlock)completedBlock {
  472. // Grab the image cache to use, choose standalone original cache firstly
  473. id<SDImageCache> imageCache = context[SDWebImageContextOriginalImageCache];
  474. if (!imageCache) {
  475. // if no standalone cache available, use default cache
  476. imageCache = context[SDWebImageContextImageCache];
  477. if (!imageCache) {
  478. imageCache = self.imageCache;
  479. }
  480. }
  481. // the original store image cache type
  482. SDImageCacheType originalStoreCacheType = SDImageCacheTypeDisk;
  483. if (context[SDWebImageContextOriginalStoreCacheType]) {
  484. originalStoreCacheType = [context[SDWebImageContextOriginalStoreCacheType] integerValue];
  485. }
  486. id<SDWebImageCacheSerializer> cacheSerializer = context[SDWebImageContextCacheSerializer];
  487. // If the original cacheType is disk, since we don't need to store the original data again
  488. // Strip the disk from the originalStoreCacheType
  489. if (cacheType == SDImageCacheTypeDisk) {
  490. if (originalStoreCacheType == SDImageCacheTypeDisk) originalStoreCacheType = SDImageCacheTypeNone;
  491. if (originalStoreCacheType == SDImageCacheTypeAll) originalStoreCacheType = SDImageCacheTypeMemory;
  492. }
  493. // Get original cache key generation without transformer
  494. NSString *key = [self originalCacheKeyForURL:url context:context];
  495. if (finished && cacheSerializer && (originalStoreCacheType == SDImageCacheTypeDisk || originalStoreCacheType == SDImageCacheTypeAll)) {
  496. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  497. NSData *newOriginalData = [cacheSerializer cacheDataWithImage:originalImage originalData:originalData imageURL:url];
  498. // Store original image and data
  499. [self storeImage:originalImage imageData:newOriginalData forKey:key options:options context:context imageCache:imageCache cacheType:originalStoreCacheType finished:finished completion:^{
  500. // Continue store cache process, transformed data is nil
  501. [self callStoreCacheProcessForOperation:operation url:url options:options context:context image:cacheImage data:cacheData cacheType:cacheType finished:finished completed:completedBlock];
  502. }];
  503. });
  504. } else {
  505. // Store original image and data
  506. [self storeImage:originalImage imageData:originalData forKey:key options:options context:context imageCache:imageCache cacheType:originalStoreCacheType finished:finished completion:^{
  507. // Continue store cache process, transformed data is nil
  508. [self callStoreCacheProcessForOperation:operation url:url options:options context:context image:cacheImage data:cacheData cacheType:cacheType finished:finished completed:completedBlock];
  509. }];
  510. }
  511. }
  512. // Store normal cache process
  513. - (void)callStoreCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  514. url:(nonnull NSURL *)url
  515. options:(SDWebImageOptions)options
  516. context:(SDWebImageContext *)context
  517. image:(nullable UIImage *)image
  518. data:(nullable NSData *)data
  519. cacheType:(SDImageCacheType)cacheType
  520. finished:(BOOL)finished
  521. completed:(nullable SDInternalCompletionBlock)completedBlock {
  522. // Grab the image cache to use
  523. id<SDImageCache> imageCache = context[SDWebImageContextImageCache];
  524. if (!imageCache) {
  525. imageCache = self.imageCache;
  526. }
  527. // the target image store cache type
  528. SDImageCacheType storeCacheType = SDImageCacheTypeAll;
  529. if (context[SDWebImageContextStoreCacheType]) {
  530. storeCacheType = [context[SDWebImageContextStoreCacheType] integerValue];
  531. }
  532. id<SDWebImageCacheSerializer> cacheSerializer = context[SDWebImageContextCacheSerializer];
  533. // transformed cache key
  534. NSString *key = [self cacheKeyForURL:url context:context];
  535. if (finished && cacheSerializer && (storeCacheType == SDImageCacheTypeDisk || storeCacheType == SDImageCacheTypeAll)) {
  536. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  537. NSData *newData = [cacheSerializer cacheDataWithImage:image originalData:data imageURL:url];
  538. // Store image and data
  539. [self storeImage:image imageData:newData forKey:key options:options context:context imageCache:imageCache cacheType:storeCacheType finished:finished completion:^{
  540. [self callCompletionBlockForOperation:operation completion:completedBlock image:image data:data error:nil cacheType:cacheType finished:finished queue:context[SDWebImageContextCallbackQueue] url:url];
  541. }];
  542. });
  543. } else {
  544. // Store image and data
  545. [self storeImage:image imageData:data forKey:key options:options context:context imageCache:imageCache cacheType:storeCacheType finished:finished completion:^{
  546. [self callCompletionBlockForOperation:operation completion:completedBlock image:image data:data error:nil cacheType:cacheType finished:finished queue:context[SDWebImageContextCallbackQueue] url:url];
  547. }];
  548. }
  549. }
  550. #pragma mark - Helper
  551. - (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation {
  552. if (!operation) {
  553. return;
  554. }
  555. SD_LOCK(_runningOperationsLock);
  556. [self.runningOperations removeObject:operation];
  557. SD_UNLOCK(_runningOperationsLock);
  558. }
  559. - (void)storeImage:(nullable UIImage *)image
  560. imageData:(nullable NSData *)data
  561. forKey:(nullable NSString *)key
  562. options:(SDWebImageOptions)options
  563. context:(nullable SDWebImageContext *)context
  564. imageCache:(nonnull id<SDImageCache>)imageCache
  565. cacheType:(SDImageCacheType)cacheType
  566. finished:(BOOL)finished
  567. completion:(nullable SDWebImageNoParamsBlock)completion {
  568. BOOL waitStoreCache = SD_OPTIONS_CONTAINS(options, SDWebImageWaitStoreCache);
  569. // Ignore progressive data cache
  570. if (!finished) {
  571. if (completion) {
  572. completion();
  573. }
  574. return;
  575. }
  576. // Check whether we should wait the store cache finished. If not, callback immediately
  577. if ([imageCache respondsToSelector:@selector(storeImage:imageData:forKey:options:context:cacheType:completion:)]) {
  578. [imageCache storeImage:image imageData:data forKey:key options:options context:context cacheType:cacheType completion:^{
  579. if (waitStoreCache) {
  580. if (completion) {
  581. completion();
  582. }
  583. }
  584. }];
  585. } else {
  586. [imageCache storeImage:image imageData:data forKey:key cacheType:cacheType completion:^{
  587. if (waitStoreCache) {
  588. if (completion) {
  589. completion();
  590. }
  591. }
  592. }];
  593. }
  594. if (!waitStoreCache) {
  595. if (completion) {
  596. completion();
  597. }
  598. }
  599. }
  600. - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
  601. completion:(nullable SDInternalCompletionBlock)completionBlock
  602. error:(nullable NSError *)error
  603. queue:(nullable SDCallbackQueue *)queue
  604. url:(nullable NSURL *)url {
  605. [self callCompletionBlockForOperation:operation completion:completionBlock image:nil data:nil error:error cacheType:SDImageCacheTypeNone finished:YES queue:queue url:url];
  606. }
  607. - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
  608. completion:(nullable SDInternalCompletionBlock)completionBlock
  609. image:(nullable UIImage *)image
  610. data:(nullable NSData *)data
  611. error:(nullable NSError *)error
  612. cacheType:(SDImageCacheType)cacheType
  613. finished:(BOOL)finished
  614. queue:(nullable SDCallbackQueue *)queue
  615. url:(nullable NSURL *)url {
  616. if (completionBlock) {
  617. [(queue ?: SDCallbackQueue.mainQueue) async:^{
  618. completionBlock(image, data, error, cacheType, finished, url);
  619. }];
  620. }
  621. }
  622. - (BOOL)shouldBlockFailedURLWithURL:(nonnull NSURL *)url
  623. error:(nonnull NSError *)error
  624. options:(SDWebImageOptions)options
  625. context:(nullable SDWebImageContext *)context {
  626. id<SDImageLoader> imageLoader = context[SDWebImageContextImageLoader];
  627. if (!imageLoader) {
  628. imageLoader = self.imageLoader;
  629. }
  630. // Check whether we should block failed url
  631. BOOL shouldBlockFailedURL;
  632. if ([self.delegate respondsToSelector:@selector(imageManager:shouldBlockFailedURL:withError:)]) {
  633. shouldBlockFailedURL = [self.delegate imageManager:self shouldBlockFailedURL:url withError:error];
  634. } else {
  635. if ([imageLoader respondsToSelector:@selector(shouldBlockFailedURLWithURL:error:options:context:)]) {
  636. shouldBlockFailedURL = [imageLoader shouldBlockFailedURLWithURL:url error:error options:options context:context];
  637. } else {
  638. shouldBlockFailedURL = [imageLoader shouldBlockFailedURLWithURL:url error:error];
  639. }
  640. }
  641. return shouldBlockFailedURL;
  642. }
  643. - (SDWebImageOptionsResult *)processedResultForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context {
  644. SDWebImageOptionsResult *result;
  645. SDWebImageMutableContext *mutableContext = [SDWebImageMutableContext dictionary];
  646. // Image Transformer from manager
  647. if (!context[SDWebImageContextImageTransformer]) {
  648. id<SDImageTransformer> transformer = self.transformer;
  649. [mutableContext setValue:transformer forKey:SDWebImageContextImageTransformer];
  650. }
  651. // Cache key filter from manager
  652. if (!context[SDWebImageContextCacheKeyFilter]) {
  653. id<SDWebImageCacheKeyFilter> cacheKeyFilter = self.cacheKeyFilter;
  654. [mutableContext setValue:cacheKeyFilter forKey:SDWebImageContextCacheKeyFilter];
  655. }
  656. // Cache serializer from manager
  657. if (!context[SDWebImageContextCacheSerializer]) {
  658. id<SDWebImageCacheSerializer> cacheSerializer = self.cacheSerializer;
  659. [mutableContext setValue:cacheSerializer forKey:SDWebImageContextCacheSerializer];
  660. }
  661. if (mutableContext.count > 0) {
  662. if (context) {
  663. [mutableContext addEntriesFromDictionary:context];
  664. }
  665. context = [mutableContext copy];
  666. }
  667. // Apply options processor
  668. if (self.optionsProcessor) {
  669. result = [self.optionsProcessor processedResultForURL:url options:options context:context];
  670. }
  671. if (!result) {
  672. // Use default options result
  673. result = [[SDWebImageOptionsResult alloc] initWithOptions:options context:context];
  674. }
  675. return result;
  676. }
  677. @end
  678. @implementation SDWebImageCombinedOperation
  679. - (BOOL)isCancelled {
  680. // Need recursive lock (user's cancel block may check isCancelled), do not use SD_LOCK
  681. @synchronized (self) {
  682. return _cancelled;
  683. }
  684. }
  685. - (void)cancel {
  686. // Need recursive lock (user's cancel block may check isCancelled), do not use SD_LOCK
  687. @synchronized(self) {
  688. if (_cancelled) {
  689. return;
  690. }
  691. _cancelled = YES;
  692. if (self.cacheOperation) {
  693. [self.cacheOperation cancel];
  694. self.cacheOperation = nil;
  695. }
  696. if (self.loaderOperation) {
  697. [self.loaderOperation cancel];
  698. self.loaderOperation = nil;
  699. }
  700. [self.manager safelyRemoveOperationFromRunning:self];
  701. }
  702. }
  703. @end