猎豆优选

AFImageDownloader.m 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024
  88. diskCapacity:150 * 1024 * 1024
  89. diskPath:@"com.alamofire.imagedownloader"];
  90. }
  91. + (NSURLSessionConfiguration *)defaultURLSessionConfiguration {
  92. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  93. //TODO set the default HTTP headers
  94. configuration.HTTPShouldSetCookies = YES;
  95. configuration.HTTPShouldUsePipelining = NO;
  96. configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
  97. configuration.allowsCellularAccess = YES;
  98. configuration.timeoutIntervalForRequest = 60.0;
  99. configuration.URLCache = [AFImageDownloader defaultURLCache];
  100. return configuration;
  101. }
  102. - (instancetype)init {
  103. NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration];
  104. AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:defaultConfiguration];
  105. sessionManager.responseSerializer = [AFImageResponseSerializer serializer];
  106. return [self initWithSessionManager:sessionManager
  107. downloadPrioritization:AFImageDownloadPrioritizationFIFO
  108. maximumActiveDownloads:4
  109. imageCache:[[AFAutoPurgingImageCache alloc] init]];
  110. }
  111. - (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
  112. downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
  113. maximumActiveDownloads:(NSInteger)maximumActiveDownloads
  114. imageCache:(id <AFImageRequestCache>)imageCache {
  115. if (self = [super init]) {
  116. self.sessionManager = sessionManager;
  117. self.downloadPrioritizaton = downloadPrioritization;
  118. self.maximumActiveDownloads = maximumActiveDownloads;
  119. self.imageCache = imageCache;
  120. self.queuedMergedTasks = [[NSMutableArray alloc] init];
  121. self.mergedTasks = [[NSMutableDictionary alloc] init];
  122. self.activeRequestCount = 0;
  123. NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]];
  124. self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL);
  125. name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]];
  126. self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
  127. }
  128. return self;
  129. }
  130. + (instancetype)defaultInstance {
  131. static AFImageDownloader *sharedInstance = nil;
  132. static dispatch_once_t onceToken;
  133. dispatch_once(&onceToken, ^{
  134. sharedInstance = [[self alloc] init];
  135. });
  136. return sharedInstance;
  137. }
  138. - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
  139. success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success
  140. failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure {
  141. return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure];
  142. }
  143. - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
  144. withReceiptID:(nonnull NSUUID *)receiptID
  145. success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
  146. failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
  147. __block NSURLSessionDataTask *task = nil;
  148. dispatch_sync(self.synchronizationQueue, ^{
  149. NSString *URLIdentifier = request.URL.absoluteString;
  150. if (URLIdentifier == nil) {
  151. if (failure) {
  152. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
  153. dispatch_async(dispatch_get_main_queue(), ^{
  154. failure(request, nil, error);
  155. });
  156. }
  157. return;
  158. }
  159. // 1) Append the success and failure blocks to a pre-existing request if it already exists
  160. AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier];
  161. if (existingMergedTask != nil) {
  162. AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure];
  163. [existingMergedTask addResponseHandler:handler];
  164. task = existingMergedTask.task;
  165. return;
  166. }
  167. // 2) Attempt to load the image from the image cache if the cache policy allows it
  168. switch (request.cachePolicy) {
  169. case NSURLRequestUseProtocolCachePolicy:
  170. case NSURLRequestReturnCacheDataElseLoad:
  171. case NSURLRequestReturnCacheDataDontLoad: {
  172. UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil];
  173. if (cachedImage != nil) {
  174. if (success) {
  175. dispatch_async(dispatch_get_main_queue(), ^{
  176. success(request, nil, cachedImage);
  177. });
  178. }
  179. return;
  180. }
  181. break;
  182. }
  183. default:
  184. break;
  185. }
  186. // 3) Create the request and set up authentication, validation and response serialization
  187. NSUUID *mergedTaskIdentifier = [NSUUID UUID];
  188. NSURLSessionDataTask *createdTask;
  189. __weak __typeof__(self) weakSelf = self;
  190. createdTask = [self.sessionManager
  191. dataTaskWithRequest:request
  192. completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
  193. dispatch_async(self.responseQueue, ^{
  194. __strong __typeof__(weakSelf) strongSelf = weakSelf;
  195. AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
  196. if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) {
  197. mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier];
  198. if (error) {
  199. for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
  200. if (handler.failureBlock) {
  201. dispatch_async(dispatch_get_main_queue(), ^{
  202. handler.failureBlock(request, (NSHTTPURLResponse*)response, error);
  203. });
  204. }
  205. }
  206. } else {
  207. [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil];
  208. for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
  209. if (handler.successBlock) {
  210. dispatch_async(dispatch_get_main_queue(), ^{
  211. handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject);
  212. });
  213. }
  214. }
  215. }
  216. }
  217. [strongSelf safelyDecrementActiveTaskCount];
  218. [strongSelf safelyStartNextTaskIfNecessary];
  219. });
  220. }];
  221. // 4) Store the response handler for use when the request completes
  222. AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID
  223. success:success
  224. failure:failure];
  225. AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc]
  226. initWithURLIdentifier:URLIdentifier
  227. identifier:mergedTaskIdentifier
  228. task:createdTask];
  229. [mergedTask addResponseHandler:handler];
  230. self.mergedTasks[URLIdentifier] = mergedTask;
  231. // 5) Either start the request or enqueue it depending on the current active request count
  232. if ([self isActiveRequestCountBelowMaximumLimit]) {
  233. [self startMergedTask:mergedTask];
  234. } else {
  235. [self enqueueMergedTask:mergedTask];
  236. }
  237. task = mergedTask.task;
  238. });
  239. if (task) {
  240. return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task];
  241. } else {
  242. return nil;
  243. }
  244. }
  245. - (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
  246. dispatch_sync(self.synchronizationQueue, ^{
  247. NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString;
  248. AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
  249. NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) {
  250. return handler.uuid == imageDownloadReceipt.receiptID;
  251. }];
  252. if (index != NSNotFound) {
  253. AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index];
  254. [mergedTask removeResponseHandler:handler];
  255. NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString];
  256. NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason};
  257. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
  258. if (handler.failureBlock) {
  259. dispatch_async(dispatch_get_main_queue(), ^{
  260. handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error);
  261. });
  262. }
  263. }
  264. if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) {
  265. [mergedTask.task cancel];
  266. [self removeMergedTaskWithURLIdentifier:URLIdentifier];
  267. }
  268. });
  269. }
  270. - (AFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
  271. __block AFImageDownloaderMergedTask *mergedTask = nil;
  272. dispatch_sync(self.synchronizationQueue, ^{
  273. mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier];
  274. });
  275. return mergedTask;
  276. }
  277. //This method should only be called from safely within the synchronizationQueue
  278. - (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
  279. AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
  280. [self.mergedTasks removeObjectForKey:URLIdentifier];
  281. return mergedTask;
  282. }
  283. - (void)safelyDecrementActiveTaskCount {
  284. dispatch_sync(self.synchronizationQueue, ^{
  285. if (self.activeRequestCount > 0) {
  286. self.activeRequestCount -= 1;
  287. }
  288. });
  289. }
  290. - (void)safelyStartNextTaskIfNecessary {
  291. dispatch_sync(self.synchronizationQueue, ^{
  292. if ([self isActiveRequestCountBelowMaximumLimit]) {
  293. while (self.queuedMergedTasks.count > 0) {
  294. AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask];
  295. if (mergedTask.task.state == NSURLSessionTaskStateSuspended) {
  296. [self startMergedTask:mergedTask];
  297. break;
  298. }
  299. }
  300. }
  301. });
  302. }
  303. - (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
  304. [mergedTask.task resume];
  305. ++self.activeRequestCount;
  306. }
  307. - (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
  308. switch (self.downloadPrioritizaton) {
  309. case AFImageDownloadPrioritizationFIFO:
  310. [self.queuedMergedTasks addObject:mergedTask];
  311. break;
  312. case AFImageDownloadPrioritizationLIFO:
  313. [self.queuedMergedTasks insertObject:mergedTask atIndex:0];
  314. break;
  315. }
  316. }
  317. - (AFImageDownloaderMergedTask *)dequeueMergedTask {
  318. AFImageDownloaderMergedTask *mergedTask = nil;
  319. mergedTask = [self.queuedMergedTasks firstObject];
  320. [self.queuedMergedTasks removeObject:mergedTask];
  321. return mergedTask;
  322. }
  323. - (BOOL)isActiveRequestCountBelowMaximumLimit {
  324. return self.activeRequestCount < self.maximumActiveDownloads;
  325. }
  326. @end
  327. #endif