SDWebImageManager.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 "SDWebImageCompat.h"
  9. #import "SDWebImageOperation.h"
  10. #import "SDWebImageDownloader.h"
  11. #import "SDImageCache.h"
  12. typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
  13. /**
  14. * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying.
  15. * This flag disable this blacklisting.
  16. */
  17. SDWebImageRetryFailed = 1 << 0,
  18. /**
  19. * By default, image downloads are started during UI interactions, this flags disable this feature,
  20. * leading to delayed download on UIScrollView deceleration for instance.
  21. */
  22. SDWebImageLowPriority = 1 << 1,
  23. /**
  24. * This flag disables on-disk caching after the download finished, only cache in memory
  25. */
  26. SDWebImageCacheMemoryOnly = 1 << 2,
  27. /**
  28. * This flag enables progressive download, the image is displayed progressively during download as a browser would do.
  29. * By default, the image is only displayed once completely downloaded.
  30. */
  31. SDWebImageProgressiveDownload = 1 << 3,
  32. /**
  33. * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.
  34. * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.
  35. * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics.
  36. * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image.
  37. *
  38. * Use this flag only if you can't make your URLs static with embedded cache busting parameter.
  39. */
  40. SDWebImageRefreshCached = 1 << 4,
  41. /**
  42. * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
  43. * extra time in background to let the request finish. If the background task expires the operation will be cancelled.
  44. */
  45. SDWebImageContinueInBackground = 1 << 5,
  46. /**
  47. * Handles cookies stored in NSHTTPCookieStore by setting
  48. * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
  49. */
  50. SDWebImageHandleCookies = 1 << 6,
  51. /**
  52. * Enable to allow untrusted SSL certificates.
  53. * Useful for testing purposes. Use with caution in production.
  54. */
  55. SDWebImageAllowInvalidSSLCertificates = 1 << 7,
  56. /**
  57. * By default, images are loaded in the order in which they were queued. This flag moves them to
  58. * the front of the queue.
  59. */
  60. SDWebImageHighPriority = 1 << 8,
  61. /**
  62. * By default, placeholder images are loaded while the image is loading. This flag will delay the loading
  63. * of the placeholder image until after the image has finished loading.
  64. */
  65. SDWebImageDelayPlaceholder = 1 << 9,
  66. /**
  67. * We usually don't call transformDownloadedImage delegate method on animated images,
  68. * as most transformation code would mangle it.
  69. * Use this flag to transform them anyway.
  70. */
  71. SDWebImageTransformAnimatedImage = 1 << 10,
  72. /**
  73. * By default, image is added to the imageView after download. But in some cases, we want to
  74. * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance)
  75. * Use this flag if you want to manually set the image in the completion when success
  76. */
  77. SDWebImageAvoidAutoSetImage = 1 << 11,
  78. /**
  79. * By default, images are decoded respecting their original size. On iOS, this flag will scale down the
  80. * images to a size compatible with the constrained memory of devices.
  81. * If `SDWebImageProgressiveDownload` flag is set the scale down is deactivated.
  82. */
  83. SDWebImageScaleDownLargeImages = 1 << 12,
  84. /**
  85. * By default, we do not query disk data when the image is cached in memory. This mask can force to query disk data at the same time.
  86. * This flag is recommend to be used with `SDWebImageQueryDiskSync` to ensure the image is loaded in the same runloop.
  87. */
  88. SDWebImageQueryDataWhenInMemory = 1 << 13,
  89. /**
  90. * By default, we query the memory cache synchronously, disk cache asynchronously. This mask can force to query disk cache synchronously to ensure that image is loaded in the same runloop.
  91. * This flag can avoid flashing during cell reuse if you disable memory cache or in some other cases.
  92. */
  93. SDWebImageQueryDiskSync = 1 << 14,
  94. /**
  95. * By default, when the cache missed, the image is download from the network. This flag can prevent network to load from cache only.
  96. */
  97. SDWebImageFromCacheOnly = 1 << 15,
  98. /**
  99. * By default, when you use `SDWebImageTransition` to do some view transition after the image load finished, this transition is only applied for image download from the network. This mask can force to apply view transition for memory and disk cache as well.
  100. */
  101. SDWebImageForceTransition = 1 << 16,
  102. /**
  103. * gif included
  104. */
  105. SDWebImageGifImageIncluded = 1 << 17
  106. };
  107. typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL);
  108. typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL);
  109. typedef NSString * _Nullable(^SDWebImageCacheKeyFilterBlock)(NSURL * _Nullable url);
  110. typedef NSData * _Nullable(^SDWebImageCacheSerializerBlock)(UIImage * _Nonnull image, NSData * _Nullable data, NSURL * _Nullable imageURL);
  111. @class SDWebImageManager;
  112. @protocol SDWebImageManagerDelegate <NSObject>
  113. @optional
  114. /**
  115. * Controls which image should be downloaded when the image is not found in the cache.
  116. *
  117. * @param imageManager The current `SDWebImageManager`
  118. * @param imageURL The url of the image to be downloaded
  119. *
  120. * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied.
  121. */
  122. - (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nullable NSURL *)imageURL;
  123. /**
  124. * Controls the complicated logic to mark as failed URLs when download error occur.
  125. * If the delegate implement this method, we will not use the built-in way to mark URL as failed based on error code;
  126. @param imageManager The current `SDWebImageManager`
  127. @param imageURL The url of the image
  128. @param error The download error for the url
  129. @return Whether to block this url or not. Return YES to mark this URL as failed.
  130. */
  131. - (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldBlockFailedURL:(nonnull NSURL *)imageURL withError:(nonnull NSError *)error;
  132. /**
  133. * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory.
  134. * NOTE: This method is called from a global queue in order to not to block the main thread.
  135. *
  136. * @param imageManager The current `SDWebImageManager`
  137. * @param image The image to transform
  138. * @param imageURL The url of the image to transform
  139. *
  140. * @return The transformed image object.
  141. */
  142. - (nullable UIImage *)imageManager:(nonnull SDWebImageManager *)imageManager transformDownloadedImage:(nullable UIImage *)image withURL:(nullable NSURL *)imageURL;
  143. @end
  144. /**
  145. * The SDWebImageManager is the class behind the UIImageView+WebCache category and likes.
  146. * It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache).
  147. * You can use this class directly to benefit from web image downloading with caching in another context than
  148. * a UIView.
  149. *
  150. * Here is a simple example of how to use SDWebImageManager:
  151. *
  152. * @code
  153. SDWebImageManager *manager = [SDWebImageManager sharedManager];
  154. [manager loadImageWithURL:imageURL
  155. options:0
  156. progress:nil
  157. completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
  158. if (image) {
  159. // do something with image
  160. }
  161. }];
  162. * @endcode
  163. */
  164. @interface SDWebImageManager : NSObject
  165. @property (weak, nonatomic, nullable) id <SDWebImageManagerDelegate> delegate;
  166. @property (strong, nonatomic, readonly, nullable) SDImageCache *imageCache;
  167. @property (strong, nonatomic, readonly, nullable) SDWebImageDownloader *imageDownloader;
  168. /**
  169. * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can
  170. * be used to remove dynamic part of an image URL.
  171. *
  172. * The following example sets a filter in the application delegate that will remove any query-string from the
  173. * URL before to use it as a cache key:
  174. *
  175. * @code
  176. SDWebImageManager.sharedManager.cacheKeyFilter = ^(NSURL * _Nullable url) {
  177. url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
  178. return [url absoluteString];
  179. };
  180. * @endcode
  181. */
  182. @property (nonatomic, copy, nullable) SDWebImageCacheKeyFilterBlock cacheKeyFilter;
  183. /**
  184. * The cache serializer is a block used to convert the decoded image, the source downloaded data, to the actual data used for storing to the disk cache. If you return nil, means to generate the data from the image instance, see `SDImageCache`.
  185. * For example, if you are using WebP images and facing the slow decoding time issue when later retriving from disk cache again. You can try to encode the decoded image to JPEG/PNG format to disk cache instead of source downloaded data.
  186. * @note The `image` arg is nonnull, but when you also provide a image transformer and the image is transformed, the `data` arg may be nil, take attention to this case.
  187. * @note This method is called from a global queue in order to not to block the main thread.
  188. * @code
  189. SDWebImageManager.sharedManager.cacheSerializer = ^NSData * _Nullable(UIImage * _Nonnull image, NSData * _Nullable data, NSURL * _Nullable imageURL) {
  190. SDImageFormat format = [NSData sd_imageFormatForImageData:data];
  191. switch (format) {
  192. case SDImageFormatWebP:
  193. return image.images ? data : nil;
  194. default:
  195. return data;
  196. }
  197. };
  198. * @endcode
  199. * The default value is nil. Means we just store the source downloaded data to disk cache.
  200. */
  201. @property (nonatomic, copy, nullable) SDWebImageCacheSerializerBlock cacheSerializer;
  202. /**
  203. * Returns global SDWebImageManager instance.
  204. *
  205. * @return SDWebImageManager shared instance
  206. */
  207. + (nonnull instancetype)sharedManager;
  208. /**
  209. * Allows to specify instance of cache and image downloader used with image manager.
  210. * @return new instance of `SDWebImageManager` with specified cache and downloader.
  211. */
  212. - (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader NS_DESIGNATED_INITIALIZER;
  213. /**
  214. * Downloads the image at the given URL if not present in cache or return the cached version otherwise.
  215. *
  216. * @param url The URL to the image
  217. * @param options A mask to specify options to use for this request
  218. * @param progressBlock A block called while image is downloading
  219. * @note the progress block is executed on a background queue
  220. * @param completedBlock A block called when operation has been completed.
  221. *
  222. * This parameter is required.
  223. *
  224. * This block has no return value and takes the requested UIImage as first parameter and the NSData representation as second parameter.
  225. * In case of error the image parameter is nil and the third parameter may contain an NSError.
  226. *
  227. * The forth parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache
  228. * or from the memory cache or from the network.
  229. *
  230. * The fith parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is
  231. * downloading. This block is thus called repeatedly with a partial image. When image is fully downloaded, the
  232. * block is called a last time with the full image and the last parameter set to YES.
  233. *
  234. * The last parameter is the original image URL
  235. *
  236. * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation
  237. */
  238. - (nullable id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
  239. options:(SDWebImageOptions)options
  240. progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
  241. completed:(nullable SDInternalCompletionBlock)completedBlock;
  242. /**
  243. * Saves image to cache for given URL
  244. *
  245. * @param image The image to cache
  246. * @param url The URL to the image
  247. *
  248. */
  249. - (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url;
  250. /**
  251. * Cancel all current operations
  252. */
  253. - (void)cancelAll;
  254. /**
  255. * Check one or more operations running
  256. */
  257. - (BOOL)isRunning;
  258. /**
  259. * Async check if image has already been cached
  260. *
  261. * @param url image url
  262. * @param completionBlock the block to be executed when the check is finished
  263. *
  264. * @note the completion block is always executed on the main queue
  265. */
  266. - (void)cachedImageExistsForURL:(nullable NSURL *)url
  267. completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock;
  268. /**
  269. * Async check if image has already been cached on disk only
  270. *
  271. * @param url image url
  272. * @param completionBlock the block to be executed when the check is finished
  273. *
  274. * @note the completion block is always executed on the main queue
  275. */
  276. - (void)diskImageExistsForURL:(nullable NSURL *)url
  277. completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock;
  278. /**
  279. *Return the cache key for a given URL
  280. */
  281. - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url;
  282. @end