SDWebImageDownloader.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 <Foundation/Foundation.h>
  9. #import "SDWebImageCompat.h"
  10. #import "SDWebImageDefine.h"
  11. #import "SDWebImageOperation.h"
  12. #import "SDWebImageDownloaderConfig.h"
  13. #import "SDWebImageDownloaderRequestModifier.h"
  14. #import "SDWebImageDownloaderResponseModifier.h"
  15. #import "SDWebImageDownloaderDecryptor.h"
  16. #import "SDImageLoader.h"
  17. /// Downloader options
  18. typedef NS_OPTIONS(NSUInteger, SDWebImageDownloaderOptions) {
  19. /**
  20. * Put the download in the low queue priority and task priority.
  21. */
  22. SDWebImageDownloaderLowPriority = 1 << 0,
  23. /**
  24. * This flag enables progressive download, the image is displayed progressively during download as a browser would do.
  25. */
  26. SDWebImageDownloaderProgressiveLoad = 1 << 1,
  27. /**
  28. * By default, request prevent the use of NSURLCache. With this flag, NSURLCache
  29. * is used with default policies.
  30. */
  31. SDWebImageDownloaderUseNSURLCache = 1 << 2,
  32. /**
  33. * Call completion block with nil image/imageData if the image was read from NSURLCache
  34. * And the error code is `SDWebImageErrorCacheNotModified`
  35. * This flag should be combined with `SDWebImageDownloaderUseNSURLCache`.
  36. */
  37. SDWebImageDownloaderIgnoreCachedResponse = 1 << 3,
  38. /**
  39. * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
  40. * extra time in background to let the request finish. If the background task expires the operation will be cancelled.
  41. */
  42. SDWebImageDownloaderContinueInBackground = 1 << 4,
  43. /**
  44. * Handles cookies stored in NSHTTPCookieStore by setting
  45. * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
  46. */
  47. SDWebImageDownloaderHandleCookies = 1 << 5,
  48. /**
  49. * Enable to allow untrusted SSL certificates.
  50. * Useful for testing purposes. Use with caution in production.
  51. */
  52. SDWebImageDownloaderAllowInvalidSSLCertificates = 1 << 6,
  53. /**
  54. * Put the download in the high queue priority and task priority.
  55. */
  56. SDWebImageDownloaderHighPriority = 1 << 7,
  57. /**
  58. * By default, images are decoded respecting their original size. On iOS, this flag will scale down the
  59. * images to a size compatible with the constrained memory of devices.
  60. * This flag take no effect if `SDWebImageDownloaderAvoidDecodeImage` is set. And it will be ignored if `SDWebImageDownloaderProgressiveLoad` is set.
  61. */
  62. SDWebImageDownloaderScaleDownLargeImages = 1 << 8,
  63. /**
  64. * By default, we will decode the image in the background during cache query and download from the network. This can help to improve performance because when rendering image on the screen, it need to be firstly decoded. But this happen on the main queue by Core Animation.
  65. * However, this process may increase the memory usage as well. If you are experiencing a issue due to excessive memory consumption, This flag can prevent decode the image.
  66. */
  67. SDWebImageDownloaderAvoidDecodeImage = 1 << 9,
  68. /**
  69. * By default, we decode the animated image. This flag can force decode the first frame only and produce the static image.
  70. */
  71. SDWebImageDownloaderDecodeFirstFrameOnly = 1 << 10,
  72. /**
  73. * By default, for `SDAnimatedImage`, we decode the animated image frame during rendering to reduce memory usage. This flag actually trigger `preloadAllAnimatedImageFrames = YES` after image load from network
  74. */
  75. SDWebImageDownloaderPreloadAllFrames = 1 << 11,
  76. /**
  77. * By default, when you use `SDWebImageContextAnimatedImageClass` context option (like using `SDAnimatedImageView` which designed to use `SDAnimatedImage`), we may still use `UIImage` when the memory cache hit, or image decoder is not available, to behave as a fallback solution.
  78. * Using this option, can ensure we always produce image with your provided class. If failed, a error with code `SDWebImageErrorBadImageData` will been used.
  79. * Note this options is not compatible with `SDWebImageDownloaderDecodeFirstFrameOnly`, which always produce a UIImage/NSImage.
  80. */
  81. SDWebImageDownloaderMatchAnimatedImageClass = 1 << 12,
  82. };
  83. FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadStartNotification;
  84. FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadReceiveResponseNotification;
  85. FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadStopNotification;
  86. FOUNDATION_EXPORT NSNotificationName _Nonnull const SDWebImageDownloadFinishNotification;
  87. typedef SDImageLoaderProgressBlock SDWebImageDownloaderProgressBlock;
  88. typedef SDImageLoaderCompletedBlock SDWebImageDownloaderCompletedBlock;
  89. /**
  90. * A token associated with each download. Can be used to cancel a download
  91. */
  92. @interface SDWebImageDownloadToken : NSObject <SDWebImageOperation>
  93. /**
  94. Cancel the current download.
  95. */
  96. - (void)cancel;
  97. /**
  98. The download's URL.
  99. */
  100. @property (nonatomic, strong, nullable, readonly) NSURL *url;
  101. /**
  102. The download's request.
  103. */
  104. @property (nonatomic, strong, nullable, readonly) NSURLRequest *request;
  105. /**
  106. The download's response.
  107. */
  108. @property (nonatomic, strong, nullable, readonly) NSURLResponse *response;
  109. /**
  110. The download's metrics. This will be nil if download operation does not support metrics.
  111. */
  112. @property (nonatomic, strong, nullable, readonly) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
  113. @end
  114. /**
  115. * Asynchronous downloader dedicated and optimized for image loading.
  116. */
  117. @interface SDWebImageDownloader : NSObject
  118. /**
  119. * Downloader Config object - storing all kind of settings.
  120. * Most config properties support dynamic changes during download, except something like `sessionConfiguration`, see `SDWebImageDownloaderConfig` for more detail.
  121. */
  122. @property (nonatomic, copy, readonly, nonnull) SDWebImageDownloaderConfig *config;
  123. /**
  124. * Set the request modifier to modify the original download request before image load.
  125. * This request modifier method will be called for each downloading image request. Return the original request means no modification. Return nil will cancel the download request.
  126. * Defaults to nil, means does not modify the original download request.
  127. * @note If you want to modify single request, consider using `SDWebImageContextDownloadRequestModifier` context option.
  128. */
  129. @property (nonatomic, strong, nullable) id<SDWebImageDownloaderRequestModifier> requestModifier;
  130. /**
  131. * Set the response modifier to modify the original download response during image load.
  132. * This request modifier method will be called for each downloading image response. Return the original response means no modification. Return nil will mark current download as cancelled.
  133. * Defaults to nil, means does not modify the original download response.
  134. * @note If you want to modify single response, consider using `SDWebImageContextDownloadResponseModifier` context option.
  135. */
  136. @property (nonatomic, strong, nullable) id<SDWebImageDownloaderResponseModifier> responseModifier;
  137. /**
  138. * Set the decryptor to decrypt the original download data before image decoding. This can be used for encrypted image data, like Base64.
  139. * This decryptor method will be called for each downloading image data. Return the original data means no modification. Return nil will mark this download failed.
  140. * Defaults to nil, means does not modify the original download data.
  141. * @note When using decryptor, progressive decoding will be disabled, to avoid data corrupt issue.
  142. * @note If you want to decrypt single download data, consider using `SDWebImageContextDownloadDecryptor` context option.
  143. */
  144. @property (nonatomic, strong, nullable) id<SDWebImageDownloaderDecryptor> decryptor;
  145. /**
  146. * The configuration in use by the internal NSURLSession. If you want to provide a custom sessionConfiguration, use `SDWebImageDownloaderConfig.sessionConfiguration` and create a new downloader instance.
  147. @note This is immutable according to NSURLSession's documentation. Mutating this object directly has no effect.
  148. */
  149. @property (nonatomic, readonly, nonnull) NSURLSessionConfiguration *sessionConfiguration;
  150. /**
  151. * Gets/Sets the download queue suspension state.
  152. */
  153. @property (nonatomic, assign, getter=isSuspended) BOOL suspended;
  154. /**
  155. * Shows the current amount of downloads that still need to be downloaded
  156. */
  157. @property (nonatomic, assign, readonly) NSUInteger currentDownloadCount;
  158. /**
  159. * Returns the global shared downloader instance. Which use the `SDWebImageDownloaderConfig.defaultDownloaderConfig` config.
  160. */
  161. @property (nonatomic, class, readonly, nonnull) SDWebImageDownloader *sharedDownloader;
  162. /**
  163. Creates an instance of a downloader with specified downloader config.
  164. You can specify session configuration, timeout or operation class through downloader config.
  165. @param config The downloader config. If you specify nil, the `defaultDownloaderConfig` will be used.
  166. @return new instance of downloader class
  167. */
  168. - (nonnull instancetype)initWithConfig:(nullable SDWebImageDownloaderConfig *)config NS_DESIGNATED_INITIALIZER;
  169. /**
  170. * Set a value for a HTTP header to be appended to each download HTTP request.
  171. *
  172. * @param value The value for the header field. Use `nil` value to remove the header field.
  173. * @param field The name of the header field to set.
  174. */
  175. - (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field;
  176. /**
  177. * Returns the value of the specified HTTP header field.
  178. *
  179. * @return The value associated with the header field field, or `nil` if there is no corresponding header field.
  180. */
  181. - (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field;
  182. /**
  183. * Creates a SDWebImageDownloader async downloader instance with a given URL
  184. *
  185. * The delegate will be informed when the image is finish downloaded or an error has happen.
  186. *
  187. * @see SDWebImageDownloaderDelegate
  188. *
  189. * @param url The URL to the image to download
  190. * @param completedBlock A block called once the download is completed.
  191. * If the download succeeded, the image parameter is set, in case of error,
  192. * error parameter is set with the error. The last parameter is always YES
  193. * if SDWebImageDownloaderProgressiveDownload isn't use. With the
  194. * SDWebImageDownloaderProgressiveDownload option, this block is called
  195. * repeatedly with the partial image object and the finished argument set to NO
  196. * before to be called a last time with the full image and finished argument
  197. * set to YES. In case of error, the finished argument is always YES.
  198. *
  199. * @return A token (SDWebImageDownloadToken) that can be used to cancel this operation
  200. */
  201. - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
  202. completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
  203. /**
  204. * Creates a SDWebImageDownloader async downloader instance with a given URL
  205. *
  206. * The delegate will be informed when the image is finish downloaded or an error has happen.
  207. *
  208. * @see SDWebImageDownloaderDelegate
  209. *
  210. * @param url The URL to the image to download
  211. * @param options The options to be used for this download
  212. * @param progressBlock A block called repeatedly while the image is downloading
  213. * @note the progress block is executed on a background queue
  214. * @param completedBlock A block called once the download is completed.
  215. * If the download succeeded, the image parameter is set, in case of error,
  216. * error parameter is set with the error. The last parameter is always YES
  217. * if SDWebImageDownloaderProgressiveLoad isn't use. With the
  218. * SDWebImageDownloaderProgressiveLoad option, this block is called
  219. * repeatedly with the partial image object and the finished argument set to NO
  220. * before to be called a last time with the full image and finished argument
  221. * set to YES. In case of error, the finished argument is always YES.
  222. *
  223. * @return A token (SDWebImageDownloadToken) that can be used to cancel this operation
  224. */
  225. - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
  226. options:(SDWebImageDownloaderOptions)options
  227. progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
  228. completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
  229. /**
  230. * Creates a SDWebImageDownloader async downloader instance with a given URL
  231. *
  232. * The delegate will be informed when the image is finish downloaded or an error has happen.
  233. *
  234. * @see SDWebImageDownloaderDelegate
  235. *
  236. * @param url The URL to the image to download
  237. * @param options The options to be used for this download
  238. * @param context A context contains different options to perform specify changes or processes, see `SDWebImageContextOption`. This hold the extra objects which `options` enum can not hold.
  239. * @param progressBlock A block called repeatedly while the image is downloading
  240. * @note the progress block is executed on a background queue
  241. * @param completedBlock A block called once the download is completed.
  242. *
  243. * @return A token (SDWebImageDownloadToken) that can be used to cancel this operation
  244. */
  245. - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
  246. options:(SDWebImageDownloaderOptions)options
  247. context:(nullable SDWebImageContext *)context
  248. progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
  249. completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
  250. /**
  251. * Cancels all download operations in the queue
  252. */
  253. - (void)cancelAllDownloads;
  254. /**
  255. * Invalidates the managed session, optionally canceling pending operations.
  256. * @note If you use custom downloader instead of the shared downloader, you need call this method when you do not use it to avoid memory leak
  257. * @param cancelPendingOperations Whether or not to cancel pending operations.
  258. * @note Calling this method on the shared downloader has no effect.
  259. */
  260. - (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations;
  261. @end
  262. /**
  263. SDWebImageDownloader is the built-in image loader conform to `SDImageLoader`. Which provide the HTTP/HTTPS/FTP download, or local file URL using NSURLSession.
  264. However, this downloader class itself also support customization for advanced users. You can specify `operationClass` in download config to custom download operation, See `SDWebImageDownloaderOperation`.
  265. If you want to provide some image loader which beyond network or local file, consider to create your own custom class conform to `SDImageLoader`.
  266. */
  267. @interface SDWebImageDownloader (SDImageLoader) <SDImageLoader>
  268. @end