SDWebImageManager.m 35 KB

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