SDWebImageManager.m 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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 *)originalCacheKeyForURL:(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. return key;
  111. }
  112. - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url context:(nullable SDWebImageContext *)context {
  113. if (!url) {
  114. return @"";
  115. }
  116. NSString *key;
  117. // Cache Key Filter
  118. id<SDWebImageCacheKeyFilter> cacheKeyFilter = self.cacheKeyFilter;
  119. if (context[SDWebImageContextCacheKeyFilter]) {
  120. cacheKeyFilter = context[SDWebImageContextCacheKeyFilter];
  121. }
  122. if (cacheKeyFilter) {
  123. key = [cacheKeyFilter cacheKeyForURL:url];
  124. } else {
  125. key = url.absoluteString;
  126. }
  127. // Thumbnail Key Appending
  128. NSValue *thumbnailSizeValue = context[SDWebImageContextImageThumbnailPixelSize];
  129. if (thumbnailSizeValue != nil) {
  130. CGSize thumbnailSize = CGSizeZero;
  131. #if SD_MAC
  132. thumbnailSize = thumbnailSizeValue.sizeValue;
  133. #else
  134. thumbnailSize = thumbnailSizeValue.CGSizeValue;
  135. #endif
  136. BOOL preserveAspectRatio = YES;
  137. NSNumber *preserveAspectRatioValue = context[SDWebImageContextImagePreserveAspectRatio];
  138. if (preserveAspectRatioValue != nil) {
  139. preserveAspectRatio = preserveAspectRatioValue.boolValue;
  140. }
  141. key = SDThumbnailedKeyForKey(key, thumbnailSize, preserveAspectRatio);
  142. }
  143. // Transformer Key Appending
  144. id<SDImageTransformer> transformer = self.transformer;
  145. if (context[SDWebImageContextImageTransformer]) {
  146. transformer = context[SDWebImageContextImageTransformer];
  147. if (![transformer conformsToProtocol:@protocol(SDImageTransformer)]) {
  148. transformer = nil;
  149. }
  150. }
  151. if (transformer) {
  152. key = SDTransformedKeyForKey(key, transformer.transformerKey);
  153. }
  154. return key;
  155. }
  156. - (SDWebImageCombinedOperation *)loadImageWithURL:(NSURL *)url options:(SDWebImageOptions)options progress:(SDImageLoaderProgressBlock)progressBlock completed:(SDInternalCompletionBlock)completedBlock {
  157. return [self loadImageWithURL:url options:options context:nil progress:progressBlock completed:completedBlock];
  158. }
  159. - (SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url
  160. options:(SDWebImageOptions)options
  161. context:(nullable SDWebImageContext *)context
  162. progress:(nullable SDImageLoaderProgressBlock)progressBlock
  163. completed:(nonnull SDInternalCompletionBlock)completedBlock {
  164. // Invoking this method without a completedBlock is pointless
  165. NSAssert(completedBlock != nil, @"If you mean to prefetch the image, use -[SDWebImagePrefetcher prefetchURLs] instead");
  166. // Very common mistake is to send the URL using NSString object instead of NSURL. For some strange reason, Xcode won't
  167. // throw any warning for this type mismatch. Here we failsafe this error by allowing URLs to be passed as NSString.
  168. if ([url isKindOfClass:NSString.class]) {
  169. url = [NSURL URLWithString:(NSString *)url];
  170. }
  171. // Prevents app crashing on argument type error like sending NSNull instead of NSURL
  172. if (![url isKindOfClass:NSURL.class]) {
  173. url = nil;
  174. }
  175. SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
  176. operation.manager = self;
  177. BOOL isFailedUrl = NO;
  178. if (url) {
  179. SD_LOCK(_failedURLsLock);
  180. isFailedUrl = [self.failedURLs containsObject:url];
  181. SD_UNLOCK(_failedURLsLock);
  182. }
  183. if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
  184. NSString *description = isFailedUrl ? @"Image url is blacklisted" : @"Image url is nil";
  185. NSInteger code = isFailedUrl ? SDWebImageErrorBlackListed : SDWebImageErrorInvalidURL;
  186. [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:code userInfo:@{NSLocalizedDescriptionKey : description}] url:url];
  187. return operation;
  188. }
  189. SD_LOCK(_runningOperationsLock);
  190. [self.runningOperations addObject:operation];
  191. SD_UNLOCK(_runningOperationsLock);
  192. // Preprocess the options and context arg to decide the final the result for manager
  193. SDWebImageOptionsResult *result = [self processedResultForURL:url options:options context:context];
  194. // Start the entry to load image from cache
  195. [self callCacheProcessForOperation:operation url:url options:result.options context:result.context progress:progressBlock completed:completedBlock];
  196. return operation;
  197. }
  198. - (void)cancelAll {
  199. SD_LOCK(_runningOperationsLock);
  200. NSSet<SDWebImageCombinedOperation *> *copiedOperations = [self.runningOperations copy];
  201. SD_UNLOCK(_runningOperationsLock);
  202. [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; // This will call `safelyRemoveOperationFromRunning:` and remove from the array
  203. }
  204. - (BOOL)isRunning {
  205. BOOL isRunning = NO;
  206. SD_LOCK(_runningOperationsLock);
  207. isRunning = (self.runningOperations.count > 0);
  208. SD_UNLOCK(_runningOperationsLock);
  209. return isRunning;
  210. }
  211. - (void)removeFailedURL:(NSURL *)url {
  212. if (!url) {
  213. return;
  214. }
  215. SD_LOCK(_failedURLsLock);
  216. [self.failedURLs removeObject:url];
  217. SD_UNLOCK(_failedURLsLock);
  218. }
  219. - (void)removeAllFailedURLs {
  220. SD_LOCK(_failedURLsLock);
  221. [self.failedURLs removeAllObjects];
  222. SD_UNLOCK(_failedURLsLock);
  223. }
  224. #pragma mark - Private
  225. // Query normal cache process
  226. - (void)callCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  227. url:(nonnull NSURL *)url
  228. options:(SDWebImageOptions)options
  229. context:(nullable SDWebImageContext *)context
  230. progress:(nullable SDImageLoaderProgressBlock)progressBlock
  231. completed:(nullable SDInternalCompletionBlock)completedBlock {
  232. // Grab the image cache to use
  233. id<SDImageCache> imageCache;
  234. if ([context[SDWebImageContextImageCache] conformsToProtocol:@protocol(SDImageCache)]) {
  235. imageCache = context[SDWebImageContextImageCache];
  236. } else {
  237. imageCache = self.imageCache;
  238. }
  239. // Get the query cache type
  240. SDImageCacheType queryCacheType = SDImageCacheTypeAll;
  241. if (context[SDWebImageContextQueryCacheType]) {
  242. queryCacheType = [context[SDWebImageContextQueryCacheType] integerValue];
  243. }
  244. // Check whether we should query cache
  245. BOOL shouldQueryCache = !SD_OPTIONS_CONTAINS(options, SDWebImageFromLoaderOnly);
  246. if (shouldQueryCache) {
  247. NSString *key = [self cacheKeyForURL:url context:context];
  248. @weakify(operation);
  249. operation.cacheOperation = [imageCache queryImageForKey:key options:options context:context cacheType:queryCacheType completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) {
  250. @strongify(operation);
  251. if (!operation || operation.isCancelled) {
  252. // Image combined operation cancelled by user
  253. [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during querying the cache"}] url:url];
  254. [self safelyRemoveOperationFromRunning:operation];
  255. return;
  256. } else if (!cachedImage) {
  257. BOOL mayInOriginalCache = context[SDWebImageContextImageTransformer] || context[SDWebImageContextImageThumbnailPixelSize];
  258. // Have a chance to query original cache instead of downloading, then applying transform
  259. // Thumbnail decoding is done inside SDImageCache's decoding part, which does not need post processing for transform
  260. if (mayInOriginalCache) {
  261. [self callOriginalCacheProcessForOperation:operation url:url options:options context:context progress:progressBlock completed:completedBlock];
  262. return;
  263. }
  264. }
  265. // Continue download process
  266. [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:cachedImage cachedData:cachedData cacheType:cacheType progress:progressBlock completed:completedBlock];
  267. }];
  268. } else {
  269. // Continue download process
  270. [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock];
  271. }
  272. }
  273. // Query original cache process
  274. - (void)callOriginalCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  275. url:(nonnull NSURL *)url
  276. options:(SDWebImageOptions)options
  277. context:(nullable SDWebImageContext *)context
  278. progress:(nullable SDImageLoaderProgressBlock)progressBlock
  279. completed:(nullable SDInternalCompletionBlock)completedBlock {
  280. // Grab the image cache to use, choose standalone original cache firstly
  281. id<SDImageCache> imageCache;
  282. if ([context[SDWebImageContextOriginalImageCache] conformsToProtocol:@protocol(SDImageCache)]) {
  283. imageCache = context[SDWebImageContextOriginalImageCache];
  284. } else {
  285. // if no standalone cache available, use default cache
  286. if ([context[SDWebImageContextImageCache] conformsToProtocol:@protocol(SDImageCache)]) {
  287. imageCache = context[SDWebImageContextImageCache];
  288. } else {
  289. imageCache = self.imageCache;
  290. }
  291. }
  292. // Get the original query cache type
  293. SDImageCacheType originalQueryCacheType = SDImageCacheTypeDisk;
  294. if (context[SDWebImageContextOriginalQueryCacheType]) {
  295. originalQueryCacheType = [context[SDWebImageContextOriginalQueryCacheType] integerValue];
  296. }
  297. // Check whether we should query original cache
  298. BOOL shouldQueryOriginalCache = (originalQueryCacheType != SDImageCacheTypeNone);
  299. if (shouldQueryOriginalCache) {
  300. // Get original cache key generation without transformer/thumbnail
  301. NSString *key = [self originalCacheKeyForURL:url context:context];
  302. @weakify(operation);
  303. operation.cacheOperation = [imageCache queryImageForKey:key options:options context:context cacheType:originalQueryCacheType completion:^(UIImage * _Nullable cachedImage, NSData * _Nullable cachedData, SDImageCacheType cacheType) {
  304. @strongify(operation);
  305. if (!operation || operation.isCancelled) {
  306. // Image combined operation cancelled by user
  307. [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during querying the cache"}] url:url];
  308. [self safelyRemoveOperationFromRunning:operation];
  309. return;
  310. } else if (!cachedImage) {
  311. // Original image cache miss. Continue download process
  312. [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock];
  313. return;
  314. }
  315. // Use the store cache process instead of downloading, and ignore .refreshCached option for now
  316. [self callStoreCacheProcessForOperation:operation url:url options:options context:context downloadedImage:cachedImage downloadedData:cachedData cacheType:cacheType finished:YES completed:completedBlock];
  317. [self safelyRemoveOperationFromRunning:operation];
  318. }];
  319. } else {
  320. // Continue download process
  321. [self callDownloadProcessForOperation:operation url:url options:options context:context cachedImage:nil cachedData:nil cacheType:SDImageCacheTypeNone progress:progressBlock completed:completedBlock];
  322. }
  323. }
  324. // Download process
  325. - (void)callDownloadProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  326. url:(nonnull NSURL *)url
  327. options:(SDWebImageOptions)options
  328. context:(SDWebImageContext *)context
  329. cachedImage:(nullable UIImage *)cachedImage
  330. cachedData:(nullable NSData *)cachedData
  331. cacheType:(SDImageCacheType)cacheType
  332. progress:(nullable SDImageLoaderProgressBlock)progressBlock
  333. completed:(nullable SDInternalCompletionBlock)completedBlock {
  334. // Grab the image loader to use
  335. id<SDImageLoader> imageLoader;
  336. if ([context[SDWebImageContextImageLoader] conformsToProtocol:@protocol(SDImageLoader)]) {
  337. imageLoader = context[SDWebImageContextImageLoader];
  338. } else {
  339. imageLoader = self.imageLoader;
  340. }
  341. // Check whether we should download image from network
  342. BOOL shouldDownload = !SD_OPTIONS_CONTAINS(options, SDWebImageFromCacheOnly);
  343. shouldDownload &= (!cachedImage || options & SDWebImageRefreshCached);
  344. shouldDownload &= (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url]);
  345. if ([imageLoader respondsToSelector:@selector(canRequestImageForURL:options:context:)]) {
  346. shouldDownload &= [imageLoader canRequestImageForURL:url options:options context:context];
  347. } else {
  348. shouldDownload &= [imageLoader canRequestImageForURL:url];
  349. }
  350. if (shouldDownload) {
  351. if (cachedImage && options & SDWebImageRefreshCached) {
  352. // If image was found in the cache but SDWebImageRefreshCached is provided, notify about the cached image
  353. // AND try to re-download it in order to let a chance to NSURLCache to refresh it from server.
  354. [self callCompletionBlockForOperation:operation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
  355. // Pass the cached image to the image loader. The image loader should check whether the remote image is equal to the cached image.
  356. SDWebImageMutableContext *mutableContext;
  357. if (context) {
  358. mutableContext = [context mutableCopy];
  359. } else {
  360. mutableContext = [NSMutableDictionary dictionary];
  361. }
  362. mutableContext[SDWebImageContextLoaderCachedImage] = cachedImage;
  363. context = [mutableContext copy];
  364. }
  365. @weakify(operation);
  366. operation.loaderOperation = [imageLoader requestImageWithURL:url options:options context:context progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) {
  367. @strongify(operation);
  368. if (!operation || operation.isCancelled) {
  369. // Image combined operation cancelled by user
  370. [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user during sending the request"}] url:url];
  371. } else if (cachedImage && options & SDWebImageRefreshCached && [error.domain isEqualToString:SDWebImageErrorDomain] && error.code == SDWebImageErrorCacheNotModified) {
  372. // Image refresh hit the NSURLCache cache, do not call the completion block
  373. } else if ([error.domain isEqualToString:SDWebImageErrorDomain] && error.code == SDWebImageErrorCancelled) {
  374. // Download operation cancelled by user before sending the request, don't block failed URL
  375. [self callCompletionBlockForOperation:operation completion:completedBlock error:error url:url];
  376. } else if (error) {
  377. [self callCompletionBlockForOperation:operation completion:completedBlock error:error url:url];
  378. BOOL shouldBlockFailedURL = [self shouldBlockFailedURLWithURL:url error:error options:options context:context];
  379. if (shouldBlockFailedURL) {
  380. SD_LOCK(self->_failedURLsLock);
  381. [self.failedURLs addObject:url];
  382. SD_UNLOCK(self->_failedURLsLock);
  383. }
  384. } else {
  385. if ((options & SDWebImageRetryFailed)) {
  386. SD_LOCK(self->_failedURLsLock);
  387. [self.failedURLs removeObject:url];
  388. SD_UNLOCK(self->_failedURLsLock);
  389. }
  390. // Continue store cache process
  391. [self callStoreCacheProcessForOperation:operation url:url options:options context:context downloadedImage:downloadedImage downloadedData:downloadedData cacheType:SDImageCacheTypeNone finished:finished completed:completedBlock];
  392. }
  393. if (finished) {
  394. [self safelyRemoveOperationFromRunning:operation];
  395. }
  396. }];
  397. } else if (cachedImage) {
  398. [self callCompletionBlockForOperation:operation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
  399. [self safelyRemoveOperationFromRunning:operation];
  400. } else {
  401. // Image not in cache and download disallowed by delegate
  402. [self callCompletionBlockForOperation:operation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES url:url];
  403. [self safelyRemoveOperationFromRunning:operation];
  404. }
  405. }
  406. // Store cache process
  407. - (void)callStoreCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  408. url:(nonnull NSURL *)url
  409. options:(SDWebImageOptions)options
  410. context:(SDWebImageContext *)context
  411. downloadedImage:(nullable UIImage *)downloadedImage
  412. downloadedData:(nullable NSData *)downloadedData
  413. cacheType:(SDImageCacheType)cacheType
  414. finished:(BOOL)finished
  415. completed:(nullable SDInternalCompletionBlock)completedBlock {
  416. // Grab the image cache to use, choose standalone original cache firstly
  417. id<SDImageCache> imageCache;
  418. if ([context[SDWebImageContextOriginalImageCache] conformsToProtocol:@protocol(SDImageCache)]) {
  419. imageCache = context[SDWebImageContextOriginalImageCache];
  420. } else {
  421. // if no standalone cache available, use default cache
  422. if ([context[SDWebImageContextImageCache] conformsToProtocol:@protocol(SDImageCache)]) {
  423. imageCache = context[SDWebImageContextImageCache];
  424. } else {
  425. imageCache = self.imageCache;
  426. }
  427. }
  428. BOOL waitStoreCache = SD_OPTIONS_CONTAINS(options, SDWebImageWaitStoreCache);
  429. // the target image store cache type
  430. SDImageCacheType storeCacheType = SDImageCacheTypeAll;
  431. if (context[SDWebImageContextStoreCacheType]) {
  432. storeCacheType = [context[SDWebImageContextStoreCacheType] integerValue];
  433. }
  434. // the original store image cache type
  435. SDImageCacheType originalStoreCacheType = SDImageCacheTypeDisk;
  436. if (context[SDWebImageContextOriginalStoreCacheType]) {
  437. originalStoreCacheType = [context[SDWebImageContextOriginalStoreCacheType] integerValue];
  438. }
  439. id<SDImageTransformer> transformer = context[SDWebImageContextImageTransformer];
  440. if (![transformer conformsToProtocol:@protocol(SDImageTransformer)]) {
  441. transformer = nil;
  442. }
  443. id<SDWebImageCacheSerializer> cacheSerializer = context[SDWebImageContextCacheSerializer];
  444. // transformer check
  445. BOOL shouldTransformImage = downloadedImage && transformer;
  446. shouldTransformImage = shouldTransformImage && (!downloadedImage.sd_isAnimated || (options & SDWebImageTransformAnimatedImage));
  447. shouldTransformImage = shouldTransformImage && (!downloadedImage.sd_isVector || (options & SDWebImageTransformVectorImage));
  448. // thumbnail check
  449. BOOL shouldThumbnailImage = context[SDWebImageContextImageThumbnailPixelSize] != nil || downloadedImage.sd_decodeOptions[SDImageCoderDecodeThumbnailPixelSize] != nil;
  450. BOOL shouldCacheOriginal = downloadedImage && finished && cacheType == SDImageCacheTypeNone;
  451. // if available, store original image to cache
  452. if (shouldCacheOriginal) {
  453. // Get original cache key generation without transformer/thumbnail
  454. NSString *key = [self originalCacheKeyForURL:url context:context];
  455. // normally use the store cache type, but if target image is transformed, use original store cache type instead
  456. SDImageCacheType targetStoreCacheType = (shouldTransformImage || shouldThumbnailImage) ? originalStoreCacheType : storeCacheType;
  457. UIImage *fullSizeImage = downloadedImage;
  458. if (shouldThumbnailImage) {
  459. // Thumbnail decoding does not keep original image
  460. // Here we only store the original data to disk for original cache key
  461. // Store thumbnail image to memory for thumbnail cache key later in `storeTransformCacheProcess`
  462. fullSizeImage = nil;
  463. }
  464. if (fullSizeImage && cacheSerializer && (targetStoreCacheType == SDImageCacheTypeDisk || targetStoreCacheType == SDImageCacheTypeAll)) {
  465. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  466. @autoreleasepool {
  467. NSData *cacheData = [cacheSerializer cacheDataWithImage:fullSizeImage originalData:downloadedData imageURL:url];
  468. [self storeImage:fullSizeImage imageData:cacheData forKey:key imageCache:imageCache cacheType:targetStoreCacheType waitStoreCache:waitStoreCache completion:^{
  469. // Continue transform process
  470. [self callTransformProcessForOperation:operation url:url options:options context:context originalImage:downloadedImage originalData:downloadedData cacheType:cacheType finished:finished completed:completedBlock];
  471. }];
  472. }
  473. });
  474. } else {
  475. [self storeImage:fullSizeImage imageData:downloadedData forKey:key imageCache:imageCache cacheType:targetStoreCacheType waitStoreCache:waitStoreCache completion:^{
  476. // Continue transform process
  477. [self callTransformProcessForOperation:operation url:url options:options context:context originalImage:downloadedImage originalData:downloadedData cacheType:cacheType finished:finished completed:completedBlock];
  478. }];
  479. }
  480. } else {
  481. // Continue transform process
  482. [self callTransformProcessForOperation:operation url:url options:options context:context originalImage:downloadedImage originalData:downloadedData cacheType:cacheType finished:finished completed:completedBlock];
  483. }
  484. }
  485. // Transform process
  486. - (void)callTransformProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  487. url:(nonnull NSURL *)url
  488. options:(SDWebImageOptions)options
  489. context:(SDWebImageContext *)context
  490. originalImage:(nullable UIImage *)originalImage
  491. originalData:(nullable NSData *)originalData
  492. cacheType:(SDImageCacheType)cacheType
  493. finished:(BOOL)finished
  494. completed:(nullable SDInternalCompletionBlock)completedBlock {
  495. // the target image store cache type
  496. SDImageCacheType storeCacheType = SDImageCacheTypeAll;
  497. if (context[SDWebImageContextStoreCacheType]) {
  498. storeCacheType = [context[SDWebImageContextStoreCacheType] integerValue];
  499. }
  500. id<SDImageTransformer> transformer = context[SDWebImageContextImageTransformer];
  501. if (![transformer conformsToProtocol:@protocol(SDImageTransformer)]) {
  502. transformer = nil;
  503. }
  504. // transformer check
  505. BOOL shouldTransformImage = originalImage && transformer;
  506. shouldTransformImage = shouldTransformImage && (!originalImage.sd_isAnimated || (options & SDWebImageTransformAnimatedImage));
  507. shouldTransformImage = shouldTransformImage && (!originalImage.sd_isVector || (options & SDWebImageTransformVectorImage));
  508. // thumbnail check
  509. // This exist when previous thumbnail pipeline callback into next full size pipeline, because we share the same URL download but need different image
  510. // Actually this is a hack, we attach the metadata into image object, which should design a better concept like `ImageInfo` and keep that around
  511. // Redecode need the full size data (progressive decoding or third-party loaders may callback nil data)
  512. BOOL shouldRedecodeFullImage = originalData && cacheType == SDImageCacheTypeNone;
  513. if (shouldRedecodeFullImage) {
  514. // If the retuened image decode options exist (some loaders impl does not use `SDImageLoaderDecode`) but does not match the options we provide, redecode
  515. SDImageCoderOptions *returnedDecodeOptions = originalImage.sd_decodeOptions;
  516. if (returnedDecodeOptions) {
  517. SDImageCoderOptions *decodeOptions = SDGetDecodeOptionsFromContext(context, options, url.absoluteString);
  518. shouldRedecodeFullImage = ![returnedDecodeOptions isEqualToDictionary:decodeOptions];
  519. } else {
  520. shouldRedecodeFullImage = NO;
  521. }
  522. }
  523. if (shouldTransformImage) {
  524. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  525. @autoreleasepool {
  526. // transformed/thumbnailed cache key
  527. NSString *key = [self cacheKeyForURL:url context:context];
  528. // Case that transformer one thumbnail, which this time need full pixel image
  529. UIImage *fullSizeImage = originalImage;
  530. BOOL imageWasRedecoded = NO;
  531. if (shouldRedecodeFullImage) {
  532. fullSizeImage = SDImageCacheDecodeImageData(originalData, key, options, context);
  533. if (fullSizeImage) {
  534. imageWasRedecoded = YES;
  535. } else {
  536. imageWasRedecoded = NO;
  537. fullSizeImage = originalImage; // Fallback
  538. }
  539. }
  540. UIImage *transformedImage = [transformer transformedImageWithImage:fullSizeImage forKey:key];
  541. if (transformedImage && finished) {
  542. BOOL imageWasTransformed = ![transformedImage isEqual:fullSizeImage];
  543. // Continue store transform cache process
  544. [self callStoreTransformCacheProcessForOperation:operation url:url options:options context:context image:transformedImage data:originalData cacheType:cacheType finished:finished transformed:imageWasTransformed || imageWasRedecoded completed:completedBlock];
  545. } else {
  546. // Continue store transform cache process
  547. [self callStoreTransformCacheProcessForOperation:operation url:url options:options context:context image:fullSizeImage data:originalData cacheType:cacheType finished:finished transformed:imageWasRedecoded completed:completedBlock];
  548. }
  549. }
  550. });
  551. } else if (shouldRedecodeFullImage) {
  552. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  553. @autoreleasepool {
  554. // Re-decode because the returned image does not match current request pipeline's context
  555. UIImage *fullSizeImage = SDImageCacheDecodeImageData(originalData, url.absoluteString, options, context);
  556. BOOL imageWasRedecoded = NO;
  557. if (fullSizeImage) {
  558. imageWasRedecoded = YES;
  559. } else {
  560. imageWasRedecoded = NO;
  561. fullSizeImage = originalImage; // Fallback
  562. }
  563. // Continue store transform cache process
  564. [self callStoreTransformCacheProcessForOperation:operation url:url options:options context:context image:fullSizeImage data:originalData cacheType:cacheType finished:finished transformed:imageWasRedecoded completed:completedBlock];
  565. }
  566. });
  567. } else {
  568. // Continue store transform cache process
  569. [self callStoreTransformCacheProcessForOperation:operation url:url options:options context:context image:originalImage data:originalData cacheType:cacheType finished:finished transformed:NO completed:completedBlock];
  570. }
  571. }
  572. - (void)callStoreTransformCacheProcessForOperation:(nonnull SDWebImageCombinedOperation *)operation
  573. url:(nonnull NSURL *)url
  574. options:(SDWebImageOptions)options
  575. context:(SDWebImageContext *)context
  576. image:(nullable UIImage *)image
  577. data:(nullable NSData *)data
  578. cacheType:(SDImageCacheType)cacheType
  579. finished:(BOOL)finished
  580. transformed:(BOOL)transformed
  581. completed:(nullable SDInternalCompletionBlock)completedBlock {
  582. // Grab the image cache to use
  583. id<SDImageCache> imageCache;
  584. if ([context[SDWebImageContextImageCache] conformsToProtocol:@protocol(SDImageCache)]) {
  585. imageCache = context[SDWebImageContextImageCache];
  586. } else {
  587. imageCache = self.imageCache;
  588. }
  589. BOOL waitStoreCache = SD_OPTIONS_CONTAINS(options, SDWebImageWaitStoreCache);
  590. // the target image store cache type
  591. SDImageCacheType storeCacheType = SDImageCacheTypeAll;
  592. if (context[SDWebImageContextStoreCacheType]) {
  593. storeCacheType = [context[SDWebImageContextStoreCacheType] integerValue];
  594. }
  595. id<SDWebImageCacheSerializer> cacheSerializer = context[SDWebImageContextCacheSerializer];
  596. // thumbnail check
  597. BOOL shouldThumbnailImage = context[SDWebImageContextImageThumbnailPixelSize] != nil || image.sd_decodeOptions[SDImageCoderDecodeThumbnailPixelSize] != nil;
  598. // Store the transformed/thumbnail image into the cache
  599. if (transformed || shouldThumbnailImage) {
  600. NSData *cacheData;
  601. // pass nil if the image was transformed/thumbnailed, so we can recalculate the data from the image
  602. if (cacheSerializer && (storeCacheType == SDImageCacheTypeDisk || storeCacheType == SDImageCacheTypeAll)) {
  603. cacheData = [cacheSerializer cacheDataWithImage:image originalData:nil imageURL:url];
  604. } else {
  605. cacheData = nil;
  606. }
  607. // transformed/thumbnailed cache key
  608. NSString *key = [self cacheKeyForURL:url context:context];
  609. [self storeImage:image imageData:cacheData forKey:key imageCache:imageCache cacheType:storeCacheType waitStoreCache:waitStoreCache completion:^{
  610. [self callCompletionBlockForOperation:operation completion:completedBlock image:image data:data error:nil cacheType:cacheType finished:finished url:url];
  611. }];
  612. } else {
  613. [self callCompletionBlockForOperation:operation completion:completedBlock image:image data:data error:nil cacheType:cacheType finished:finished url:url];
  614. }
  615. }
  616. #pragma mark - Helper
  617. - (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation {
  618. if (!operation) {
  619. return;
  620. }
  621. SD_LOCK(_runningOperationsLock);
  622. [self.runningOperations removeObject:operation];
  623. SD_UNLOCK(_runningOperationsLock);
  624. }
  625. - (void)storeImage:(nullable UIImage *)image
  626. imageData:(nullable NSData *)data
  627. forKey:(nullable NSString *)key
  628. imageCache:(nonnull id<SDImageCache>)imageCache
  629. cacheType:(SDImageCacheType)cacheType
  630. waitStoreCache:(BOOL)waitStoreCache
  631. completion:(nullable SDWebImageNoParamsBlock)completion {
  632. // Check whether we should wait the store cache finished. If not, callback immediately
  633. [imageCache storeImage:image imageData:data forKey:key cacheType:cacheType completion:^{
  634. if (waitStoreCache) {
  635. if (completion) {
  636. completion();
  637. }
  638. }
  639. }];
  640. if (!waitStoreCache) {
  641. if (completion) {
  642. completion();
  643. }
  644. }
  645. }
  646. - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
  647. completion:(nullable SDInternalCompletionBlock)completionBlock
  648. error:(nullable NSError *)error
  649. url:(nullable NSURL *)url {
  650. [self callCompletionBlockForOperation:operation completion:completionBlock image:nil data:nil error:error cacheType:SDImageCacheTypeNone finished:YES url:url];
  651. }
  652. - (void)callCompletionBlockForOperation:(nullable SDWebImageCombinedOperation*)operation
  653. completion:(nullable SDInternalCompletionBlock)completionBlock
  654. image:(nullable UIImage *)image
  655. data:(nullable NSData *)data
  656. error:(nullable NSError *)error
  657. cacheType:(SDImageCacheType)cacheType
  658. finished:(BOOL)finished
  659. url:(nullable NSURL *)url {
  660. dispatch_main_async_safe(^{
  661. if (completionBlock) {
  662. completionBlock(image, data, error, cacheType, finished, url);
  663. }
  664. });
  665. }
  666. - (BOOL)shouldBlockFailedURLWithURL:(nonnull NSURL *)url
  667. error:(nonnull NSError *)error
  668. options:(SDWebImageOptions)options
  669. context:(nullable SDWebImageContext *)context {
  670. id<SDImageLoader> imageLoader;
  671. if ([context[SDWebImageContextImageLoader] conformsToProtocol:@protocol(SDImageLoader)]) {
  672. imageLoader = context[SDWebImageContextImageLoader];
  673. } else {
  674. imageLoader = self.imageLoader;
  675. }
  676. // Check whether we should block failed url
  677. BOOL shouldBlockFailedURL;
  678. if ([self.delegate respondsToSelector:@selector(imageManager:shouldBlockFailedURL:withError:)]) {
  679. shouldBlockFailedURL = [self.delegate imageManager:self shouldBlockFailedURL:url withError:error];
  680. } else {
  681. if ([imageLoader respondsToSelector:@selector(shouldBlockFailedURLWithURL:error:options:context:)]) {
  682. shouldBlockFailedURL = [imageLoader shouldBlockFailedURLWithURL:url error:error options:options context:context];
  683. } else {
  684. shouldBlockFailedURL = [imageLoader shouldBlockFailedURLWithURL:url error:error];
  685. }
  686. }
  687. return shouldBlockFailedURL;
  688. }
  689. - (SDWebImageOptionsResult *)processedResultForURL:(NSURL *)url options:(SDWebImageOptions)options context:(SDWebImageContext *)context {
  690. SDWebImageOptionsResult *result;
  691. SDWebImageMutableContext *mutableContext = [SDWebImageMutableContext dictionary];
  692. // Image Transformer from manager
  693. if (!context[SDWebImageContextImageTransformer]) {
  694. id<SDImageTransformer> transformer = self.transformer;
  695. [mutableContext setValue:transformer forKey:SDWebImageContextImageTransformer];
  696. }
  697. // Cache key filter from manager
  698. if (!context[SDWebImageContextCacheKeyFilter]) {
  699. id<SDWebImageCacheKeyFilter> cacheKeyFilter = self.cacheKeyFilter;
  700. [mutableContext setValue:cacheKeyFilter forKey:SDWebImageContextCacheKeyFilter];
  701. }
  702. // Cache serializer from manager
  703. if (!context[SDWebImageContextCacheSerializer]) {
  704. id<SDWebImageCacheSerializer> cacheSerializer = self.cacheSerializer;
  705. [mutableContext setValue:cacheSerializer forKey:SDWebImageContextCacheSerializer];
  706. }
  707. if (mutableContext.count > 0) {
  708. if (context) {
  709. [mutableContext addEntriesFromDictionary:context];
  710. }
  711. context = [mutableContext copy];
  712. }
  713. // Apply options processor
  714. if (self.optionsProcessor) {
  715. result = [self.optionsProcessor processedResultForURL:url options:options context:context];
  716. }
  717. if (!result) {
  718. // Use default options result
  719. result = [[SDWebImageOptionsResult alloc] initWithOptions:options context:context];
  720. }
  721. return result;
  722. }
  723. @end
  724. @implementation SDWebImageCombinedOperation
  725. - (void)cancel {
  726. @synchronized(self) {
  727. if (self.isCancelled) {
  728. return;
  729. }
  730. self.cancelled = YES;
  731. if (self.cacheOperation) {
  732. [self.cacheOperation cancel];
  733. self.cacheOperation = nil;
  734. }
  735. if (self.loaderOperation) {
  736. [self.loaderOperation cancel];
  737. self.loaderOperation = nil;
  738. }
  739. [self.manager safelyRemoveOperationFromRunning:self];
  740. }
  741. }
  742. @end