AFImageDownloader.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. // AFImageDownloader.m
  2. // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. #import <TargetConditionals.h>
  22. #if TARGET_OS_IOS || TARGET_OS_TV
  23. #import "AFImageDownloader.h"
  24. #import "AFHTTPSessionManager.h"
  25. @interface AFImageDownloaderResponseHandler : NSObject
  26. @property (nonatomic, strong) NSUUID *uuid;
  27. @property (nonatomic, copy) void (^successBlock)(NSURLRequest*, NSHTTPURLResponse*, UIImage*);
  28. @property (nonatomic, copy) void (^failureBlock)(NSURLRequest*, NSHTTPURLResponse*, NSError*);
  29. @end
  30. @implementation AFImageDownloaderResponseHandler
  31. - (instancetype)initWithUUID:(NSUUID *)uuid
  32. success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
  33. failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
  34. if (self = [self init]) {
  35. self.uuid = uuid;
  36. self.successBlock = success;
  37. self.failureBlock = failure;
  38. }
  39. return self;
  40. }
  41. - (NSString *)description {
  42. return [NSString stringWithFormat: @"<AFImageDownloaderResponseHandler>UUID: %@", [self.uuid UUIDString]];
  43. }
  44. @end
  45. @interface AFImageDownloaderMergedTask : NSObject
  46. @property (nonatomic, strong) NSString *URLIdentifier;
  47. @property (nonatomic, strong) NSUUID *identifier;
  48. @property (nonatomic, strong) NSURLSessionDataTask *task;
  49. @property (nonatomic, strong) NSMutableArray <AFImageDownloaderResponseHandler*> *responseHandlers;
  50. @end
  51. @implementation AFImageDownloaderMergedTask
  52. - (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task {
  53. if (self = [self init]) {
  54. self.URLIdentifier = URLIdentifier;
  55. self.task = task;
  56. self.identifier = identifier;
  57. self.responseHandlers = [[NSMutableArray alloc] init];
  58. }
  59. return self;
  60. }
  61. - (void)addResponseHandler:(AFImageDownloaderResponseHandler*)handler {
  62. [self.responseHandlers addObject:handler];
  63. }
  64. - (void)removeResponseHandler:(AFImageDownloaderResponseHandler*)handler {
  65. [self.responseHandlers removeObject:handler];
  66. }
  67. @end
  68. @implementation AFImageDownloadReceipt
  69. - (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task {
  70. if (self = [self init]) {
  71. self.receiptID = receiptID;
  72. self.task = task;
  73. }
  74. return self;
  75. }
  76. @end
  77. @interface AFImageDownloader ()
  78. @property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
  79. @property (nonatomic, strong) dispatch_queue_t responseQueue;
  80. @property (nonatomic, assign) NSInteger maximumActiveDownloads;
  81. @property (nonatomic, assign) NSInteger activeRequestCount;
  82. @property (nonatomic, strong) NSMutableArray *queuedMergedTasks;
  83. @property (nonatomic, strong) NSMutableDictionary *mergedTasks;
  84. @end
  85. @implementation AFImageDownloader
  86. + (NSURLCache *)defaultURLCache {
  87. // It's been discovered that a crash will occur on certain versions
  88. // of iOS if you customize the cache.
  89. //
  90. // More info can be found here: https://devforums.apple.com/message/1102182#1102182
  91. //
  92. // When iOS 7 support is dropped, this should be modified to use
  93. // NSProcessInfo methods instead.
  94. if ([[[UIDevice currentDevice] systemVersion] compare:@"8.2" options:NSNumericSearch] == NSOrderedAscending) {
  95. return [NSURLCache sharedURLCache];
  96. }
  97. return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024
  98. diskCapacity:150 * 1024 * 1024
  99. diskPath:@"com.alamofire.imagedownloader"];
  100. }
  101. + (NSURLSessionConfiguration *)defaultURLSessionConfiguration {
  102. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  103. //TODO set the default HTTP headers
  104. configuration.HTTPShouldSetCookies = YES;
  105. configuration.HTTPShouldUsePipelining = NO;
  106. configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
  107. configuration.allowsCellularAccess = YES;
  108. configuration.timeoutIntervalForRequest = 60.0;
  109. configuration.URLCache = [AFImageDownloader defaultURLCache];
  110. return configuration;
  111. }
  112. - (instancetype)init {
  113. NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration];
  114. return [self initWithSessionConfiguration:defaultConfiguration];
  115. }
  116. - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
  117. AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
  118. sessionManager.responseSerializer = [AFImageResponseSerializer serializer];
  119. return [self initWithSessionManager:sessionManager
  120. downloadPrioritization:AFImageDownloadPrioritizationFIFO
  121. maximumActiveDownloads:4
  122. imageCache:[[AFAutoPurgingImageCache alloc] init]];
  123. }
  124. - (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
  125. downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
  126. maximumActiveDownloads:(NSInteger)maximumActiveDownloads
  127. imageCache:(id <AFImageRequestCache>)imageCache {
  128. if (self = [super init]) {
  129. self.sessionManager = sessionManager;
  130. self.downloadPrioritizaton = downloadPrioritization;
  131. self.maximumActiveDownloads = maximumActiveDownloads;
  132. self.imageCache = imageCache;
  133. self.queuedMergedTasks = [[NSMutableArray alloc] init];
  134. self.mergedTasks = [[NSMutableDictionary alloc] init];
  135. self.activeRequestCount = 0;
  136. NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]];
  137. self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL);
  138. name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]];
  139. self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
  140. }
  141. return self;
  142. }
  143. + (instancetype)defaultInstance {
  144. static AFImageDownloader *sharedInstance = nil;
  145. static dispatch_once_t onceToken;
  146. dispatch_once(&onceToken, ^{
  147. sharedInstance = [[self alloc] init];
  148. });
  149. return sharedInstance;
  150. }
  151. - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
  152. success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success
  153. failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure {
  154. return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure];
  155. }
  156. - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
  157. withReceiptID:(nonnull NSUUID *)receiptID
  158. success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
  159. failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
  160. __block NSURLSessionDataTask *task = nil;
  161. dispatch_sync(self.synchronizationQueue, ^{
  162. NSString *URLIdentifier = request.URL.absoluteString;
  163. if (URLIdentifier == nil) {
  164. if (failure) {
  165. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
  166. dispatch_async(dispatch_get_main_queue(), ^{
  167. failure(request, nil, error);
  168. });
  169. }
  170. return;
  171. }
  172. // 1) Append the success and failure blocks to a pre-existing request if it already exists
  173. AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier];
  174. if (existingMergedTask != nil) {
  175. AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure];
  176. [existingMergedTask addResponseHandler:handler];
  177. task = existingMergedTask.task;
  178. return;
  179. }
  180. // 2) Attempt to load the image from the image cache if the cache policy allows it
  181. switch (request.cachePolicy) {
  182. case NSURLRequestUseProtocolCachePolicy:
  183. case NSURLRequestReturnCacheDataElseLoad:
  184. case NSURLRequestReturnCacheDataDontLoad: {
  185. UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil];
  186. if (cachedImage != nil) {
  187. if (success) {
  188. dispatch_async(dispatch_get_main_queue(), ^{
  189. success(request, nil, cachedImage);
  190. });
  191. }
  192. return;
  193. }
  194. break;
  195. }
  196. default:
  197. break;
  198. }
  199. // 3) Create the request and set up authentication, validation and response serialization
  200. NSUUID *mergedTaskIdentifier = [NSUUID UUID];
  201. NSURLSessionDataTask *createdTask;
  202. __weak __typeof__(self) weakSelf = self;
  203. createdTask = [self.sessionManager
  204. dataTaskWithRequest:request
  205. uploadProgress:nil
  206. downloadProgress:nil
  207. completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  208. dispatch_async(self.responseQueue, ^{
  209. __strong __typeof__(weakSelf) strongSelf = weakSelf;
  210. AFImageDownloaderMergedTask *mergedTask = strongSelf.mergedTasks[URLIdentifier];
  211. if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) {
  212. mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier];
  213. if (error) {
  214. for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
  215. if (handler.failureBlock) {
  216. dispatch_async(dispatch_get_main_queue(), ^{
  217. handler.failureBlock(request, (NSHTTPURLResponse*)response, error);
  218. });
  219. }
  220. }
  221. } else {
  222. if ([strongSelf.imageCache shouldCacheImage:responseObject forRequest:request withAdditionalIdentifier:nil]) {
  223. [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil];
  224. }
  225. for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
  226. if (handler.successBlock) {
  227. dispatch_async(dispatch_get_main_queue(), ^{
  228. handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject);
  229. });
  230. }
  231. }
  232. }
  233. }
  234. [strongSelf safelyDecrementActiveTaskCount];
  235. [strongSelf safelyStartNextTaskIfNecessary];
  236. });
  237. }];
  238. // 4) Store the response handler for use when the request completes
  239. AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID
  240. success:success
  241. failure:failure];
  242. AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc]
  243. initWithURLIdentifier:URLIdentifier
  244. identifier:mergedTaskIdentifier
  245. task:createdTask];
  246. [mergedTask addResponseHandler:handler];
  247. self.mergedTasks[URLIdentifier] = mergedTask;
  248. // 5) Either start the request or enqueue it depending on the current active request count
  249. if ([self isActiveRequestCountBelowMaximumLimit]) {
  250. [self startMergedTask:mergedTask];
  251. } else {
  252. [self enqueueMergedTask:mergedTask];
  253. }
  254. task = mergedTask.task;
  255. });
  256. if (task) {
  257. return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task];
  258. } else {
  259. return nil;
  260. }
  261. }
  262. - (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
  263. dispatch_sync(self.synchronizationQueue, ^{
  264. NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString;
  265. AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
  266. NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) {
  267. return handler.uuid == imageDownloadReceipt.receiptID;
  268. }];
  269. if (index != NSNotFound) {
  270. AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index];
  271. [mergedTask removeResponseHandler:handler];
  272. NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString];
  273. NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason};
  274. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
  275. if (handler.failureBlock) {
  276. dispatch_async(dispatch_get_main_queue(), ^{
  277. handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error);
  278. });
  279. }
  280. }
  281. if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) {
  282. [mergedTask.task cancel];
  283. [self removeMergedTaskWithURLIdentifier:URLIdentifier];
  284. }
  285. });
  286. }
  287. - (AFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
  288. __block AFImageDownloaderMergedTask *mergedTask = nil;
  289. dispatch_sync(self.synchronizationQueue, ^{
  290. mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier];
  291. });
  292. return mergedTask;
  293. }
  294. //This method should only be called from safely within the synchronizationQueue
  295. - (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
  296. AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
  297. [self.mergedTasks removeObjectForKey:URLIdentifier];
  298. return mergedTask;
  299. }
  300. - (void)safelyDecrementActiveTaskCount {
  301. dispatch_sync(self.synchronizationQueue, ^{
  302. if (self.activeRequestCount > 0) {
  303. self.activeRequestCount -= 1;
  304. }
  305. });
  306. }
  307. - (void)safelyStartNextTaskIfNecessary {
  308. dispatch_sync(self.synchronizationQueue, ^{
  309. if ([self isActiveRequestCountBelowMaximumLimit]) {
  310. while (self.queuedMergedTasks.count > 0) {
  311. AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask];
  312. if (mergedTask.task.state == NSURLSessionTaskStateSuspended) {
  313. [self startMergedTask:mergedTask];
  314. break;
  315. }
  316. }
  317. }
  318. });
  319. }
  320. - (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
  321. [mergedTask.task resume];
  322. ++self.activeRequestCount;
  323. }
  324. - (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
  325. switch (self.downloadPrioritizaton) {
  326. case AFImageDownloadPrioritizationFIFO:
  327. [self.queuedMergedTasks addObject:mergedTask];
  328. break;
  329. case AFImageDownloadPrioritizationLIFO:
  330. [self.queuedMergedTasks insertObject:mergedTask atIndex:0];
  331. break;
  332. }
  333. }
  334. - (AFImageDownloaderMergedTask *)dequeueMergedTask {
  335. AFImageDownloaderMergedTask *mergedTask = nil;
  336. mergedTask = [self.queuedMergedTasks firstObject];
  337. [self.queuedMergedTasks removeObject:mergedTask];
  338. return mergedTask;
  339. }
  340. - (BOOL)isActiveRequestCountBelowMaximumLimit {
  341. return self.activeRequestCount < self.maximumActiveDownloads;
  342. }
  343. @end
  344. #endif