Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

AFURLSessionManager.m 54KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  1. // AFURLSessionManager.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 "AFURLSessionManager.h"
  22. #import <objc/runtime.h>
  23. #ifndef NSFoundationVersionNumber_iOS_8_0
  24. #define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug 1140.11
  25. #else
  26. #define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug NSFoundationVersionNumber_iOS_8_0
  27. #endif
  28. static dispatch_queue_t url_session_manager_creation_queue() {
  29. static dispatch_queue_t af_url_session_manager_creation_queue;
  30. static dispatch_once_t onceToken;
  31. dispatch_once(&onceToken, ^{
  32. af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL);
  33. });
  34. return af_url_session_manager_creation_queue;
  35. }
  36. static void url_session_manager_create_task_safely(dispatch_block_t block) {
  37. if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) {
  38. // Fix of bug
  39. // Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8)
  40. // Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093
  41. dispatch_sync(url_session_manager_creation_queue(), block);
  42. } else {
  43. block();
  44. }
  45. }
  46. static dispatch_queue_t url_session_manager_processing_queue() {
  47. static dispatch_queue_t af_url_session_manager_processing_queue;
  48. static dispatch_once_t onceToken;
  49. dispatch_once(&onceToken, ^{
  50. af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT);
  51. });
  52. return af_url_session_manager_processing_queue;
  53. }
  54. static dispatch_group_t url_session_manager_completion_group() {
  55. static dispatch_group_t af_url_session_manager_completion_group;
  56. static dispatch_once_t onceToken;
  57. dispatch_once(&onceToken, ^{
  58. af_url_session_manager_completion_group = dispatch_group_create();
  59. });
  60. return af_url_session_manager_completion_group;
  61. }
  62. NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume";
  63. NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete";
  64. NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend";
  65. NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
  66. NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
  67. NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse";
  68. NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer";
  69. NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata";
  70. NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error";
  71. NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath";
  72. static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock";
  73. static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3;
  74. typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error);
  75. typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
  76. typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request);
  77. typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
  78. typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session);
  79. typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task);
  80. typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend);
  81. typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error);
  82. typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response);
  83. typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
  84. typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
  85. typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse);
  86. typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location);
  87. typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
  88. typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes);
  89. typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *);
  90. typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error);
  91. #pragma mark -
  92. @interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
  93. @property (nonatomic, weak) AFURLSessionManager *manager;
  94. @property (nonatomic, strong) NSMutableData *mutableData;
  95. @property (nonatomic, strong) NSProgress *uploadProgress;
  96. @property (nonatomic, strong) NSProgress *downloadProgress;
  97. @property (nonatomic, copy) NSURL *downloadFileURL;
  98. @property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
  99. @property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock;
  100. @property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock;
  101. @property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler;
  102. @end
  103. @implementation AFURLSessionManagerTaskDelegate
  104. - (instancetype)init {
  105. self = [super init];
  106. if (!self) {
  107. return nil;
  108. }
  109. self.mutableData = [NSMutableData data];
  110. self.uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
  111. self.uploadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown;
  112. self.downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
  113. self.downloadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown;
  114. return self;
  115. }
  116. #pragma mark - NSProgress Tracking
  117. - (void)setupProgressForTask:(NSURLSessionTask *)task {
  118. __weak __typeof__(task) weakTask = task;
  119. self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
  120. self.downloadProgress.totalUnitCount = task.countOfBytesExpectedToReceive;
  121. [self.uploadProgress setCancellable:YES];
  122. [self.uploadProgress setCancellationHandler:^{
  123. __typeof__(weakTask) strongTask = weakTask;
  124. [strongTask cancel];
  125. }];
  126. [self.uploadProgress setPausable:YES];
  127. [self.uploadProgress setPausingHandler:^{
  128. __typeof__(weakTask) strongTask = weakTask;
  129. [strongTask suspend];
  130. }];
  131. if ([self.uploadProgress respondsToSelector:@selector(setResumingHandler:)]) {
  132. [self.uploadProgress setResumingHandler:^{
  133. __typeof__(weakTask) strongTask = weakTask;
  134. [strongTask resume];
  135. }];
  136. }
  137. [self.downloadProgress setCancellable:YES];
  138. [self.downloadProgress setCancellationHandler:^{
  139. __typeof__(weakTask) strongTask = weakTask;
  140. [strongTask cancel];
  141. }];
  142. [self.downloadProgress setPausable:YES];
  143. [self.downloadProgress setPausingHandler:^{
  144. __typeof__(weakTask) strongTask = weakTask;
  145. [strongTask suspend];
  146. }];
  147. if ([self.downloadProgress respondsToSelector:@selector(setResumingHandler:)]) {
  148. [self.downloadProgress setResumingHandler:^{
  149. __typeof__(weakTask) strongTask = weakTask;
  150. [strongTask resume];
  151. }];
  152. }
  153. [task addObserver:self
  154. forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))
  155. options:NSKeyValueObservingOptionNew
  156. context:NULL];
  157. [task addObserver:self
  158. forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))
  159. options:NSKeyValueObservingOptionNew
  160. context:NULL];
  161. [task addObserver:self
  162. forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))
  163. options:NSKeyValueObservingOptionNew
  164. context:NULL];
  165. [task addObserver:self
  166. forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend))
  167. options:NSKeyValueObservingOptionNew
  168. context:NULL];
  169. [self.downloadProgress addObserver:self
  170. forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
  171. options:NSKeyValueObservingOptionNew
  172. context:NULL];
  173. [self.uploadProgress addObserver:self
  174. forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
  175. options:NSKeyValueObservingOptionNew
  176. context:NULL];
  177. }
  178. - (void)cleanUpProgressForTask:(NSURLSessionTask *)task {
  179. [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))];
  180. [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))];
  181. [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))];
  182. [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend))];
  183. [self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
  184. [self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
  185. }
  186. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
  187. if ([object isKindOfClass:[NSURLSessionTask class]] || [object isKindOfClass:[NSURLSessionDownloadTask class]]) {
  188. if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
  189. self.downloadProgress.completedUnitCount = [change[NSKeyValueChangeNewKey] longLongValue];
  190. } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]) {
  191. self.downloadProgress.totalUnitCount = [change[NSKeyValueChangeNewKey] longLongValue];
  192. } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
  193. self.uploadProgress.completedUnitCount = [change[NSKeyValueChangeNewKey] longLongValue];
  194. } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]) {
  195. self.uploadProgress.totalUnitCount = [change[NSKeyValueChangeNewKey] longLongValue];
  196. }
  197. }
  198. else if ([object isEqual:self.downloadProgress]) {
  199. if (self.downloadProgressBlock) {
  200. self.downloadProgressBlock(object);
  201. }
  202. }
  203. else if ([object isEqual:self.uploadProgress]) {
  204. if (self.uploadProgressBlock) {
  205. self.uploadProgressBlock(object);
  206. }
  207. }
  208. }
  209. #pragma mark - NSURLSessionTaskDelegate
  210. - (void)URLSession:(__unused NSURLSession *)session
  211. task:(NSURLSessionTask *)task
  212. didCompleteWithError:(NSError *)error
  213. {
  214. __strong AFURLSessionManager *manager = self.manager;
  215. __block id responseObject = nil;
  216. __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
  217. userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
  218. //Performance Improvement from #2672
  219. NSData *data = nil;
  220. if (self.mutableData) {
  221. data = [self.mutableData copy];
  222. //We no longer need the reference, so nil it out to gain back some memory.
  223. self.mutableData = nil;
  224. }
  225. if (self.downloadFileURL) {
  226. userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
  227. } else if (data) {
  228. userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
  229. }
  230. if (error) {
  231. userInfo[AFNetworkingTaskDidCompleteErrorKey] = error;
  232. dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
  233. if (self.completionHandler) {
  234. self.completionHandler(task.response, responseObject, error);
  235. }
  236. dispatch_async(dispatch_get_main_queue(), ^{
  237. [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
  238. });
  239. });
  240. } else {
  241. dispatch_async(url_session_manager_processing_queue(), ^{
  242. NSError *serializationError = nil;
  243. responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError];
  244. if (self.downloadFileURL) {
  245. responseObject = self.downloadFileURL;
  246. }
  247. if (responseObject) {
  248. userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
  249. }
  250. if (serializationError) {
  251. userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
  252. }
  253. dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
  254. if (self.completionHandler) {
  255. self.completionHandler(task.response, responseObject, serializationError);
  256. }
  257. dispatch_async(dispatch_get_main_queue(), ^{
  258. [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
  259. });
  260. });
  261. });
  262. }
  263. }
  264. #pragma mark - NSURLSessionDataTaskDelegate
  265. - (void)URLSession:(__unused NSURLSession *)session
  266. dataTask:(__unused NSURLSessionDataTask *)dataTask
  267. didReceiveData:(NSData *)data
  268. {
  269. [self.mutableData appendData:data];
  270. }
  271. #pragma mark - NSURLSessionDownloadTaskDelegate
  272. - (void)URLSession:(NSURLSession *)session
  273. downloadTask:(NSURLSessionDownloadTask *)downloadTask
  274. didFinishDownloadingToURL:(NSURL *)location
  275. {
  276. NSError *fileManagerError = nil;
  277. self.downloadFileURL = nil;
  278. if (self.downloadTaskDidFinishDownloading) {
  279. self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
  280. if (self.downloadFileURL) {
  281. [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError];
  282. if (fileManagerError) {
  283. [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo];
  284. }
  285. }
  286. }
  287. }
  288. @end
  289. #pragma mark -
  290. /**
  291. * A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`.
  292. *
  293. * See:
  294. * - https://github.com/AFNetworking/AFNetworking/issues/1477
  295. * - https://github.com/AFNetworking/AFNetworking/issues/2638
  296. * - https://github.com/AFNetworking/AFNetworking/pull/2702
  297. */
  298. static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) {
  299. Method originalMethod = class_getInstanceMethod(theClass, originalSelector);
  300. Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector);
  301. method_exchangeImplementations(originalMethod, swizzledMethod);
  302. }
  303. static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) {
  304. return class_addMethod(theClass, selector, method_getImplementation(method), method_getTypeEncoding(method));
  305. }
  306. static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume";
  307. static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend";
  308. @interface _AFURLSessionTaskSwizzling : NSObject
  309. @end
  310. @implementation _AFURLSessionTaskSwizzling
  311. + (void)load {
  312. /**
  313. WARNING: Trouble Ahead
  314. https://github.com/AFNetworking/AFNetworking/pull/2702
  315. */
  316. if (NSClassFromString(@"NSURLSessionTask")) {
  317. /**
  318. iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky.
  319. Many Unit Tests have been built to validate as much of this behavior has possible.
  320. Here is what we know:
  321. - NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back.
  322. - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there.
  323. - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`.
  324. - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`.
  325. - On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled.
  326. - On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled.
  327. - Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there.
  328. Some Assumptions:
  329. - No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it.
  330. - No background task classes override `resume` or `suspend`
  331. The current solution:
  332. 1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task.
  333. 2) Grab a pointer to the original implementation of `af_resume`
  334. 3) Check to see if the current class has an implementation of resume. If so, continue to step 4.
  335. 4) Grab the super class of the current class.
  336. 5) Grab a pointer for the current class to the current implementation of `resume`.
  337. 6) Grab a pointer for the super class to the current implementation of `resume`.
  338. 7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods
  339. 8) Set the current class to the super class, and repeat steps 3-8
  340. */
  341. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
  342. NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration];
  343. #pragma GCC diagnostic push
  344. #pragma GCC diagnostic ignored "-Wnonnull"
  345. NSURLSessionDataTask *localDataTask = [session dataTaskWithURL:nil];
  346. #pragma clang diagnostic pop
  347. IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self class], @selector(af_resume)));
  348. Class currentClass = [localDataTask class];
  349. while (class_getInstanceMethod(currentClass, @selector(resume))) {
  350. Class superClass = [currentClass superclass];
  351. IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume)));
  352. IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume)));
  353. if (classResumeIMP != superclassResumeIMP &&
  354. originalAFResumeIMP != classResumeIMP) {
  355. [self swizzleResumeAndSuspendMethodForClass:currentClass];
  356. }
  357. currentClass = [currentClass superclass];
  358. }
  359. [localDataTask cancel];
  360. [session finishTasksAndInvalidate];
  361. }
  362. }
  363. + (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass {
  364. Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume));
  365. Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend));
  366. if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) {
  367. af_swizzleSelector(theClass, @selector(resume), @selector(af_resume));
  368. }
  369. if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) {
  370. af_swizzleSelector(theClass, @selector(suspend), @selector(af_suspend));
  371. }
  372. }
  373. - (NSURLSessionTaskState)state {
  374. NSAssert(NO, @"State method should never be called in the actual dummy class");
  375. return NSURLSessionTaskStateCanceling;
  376. }
  377. - (void)af_resume {
  378. NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
  379. NSURLSessionTaskState state = [self state];
  380. [self af_resume];
  381. if (state != NSURLSessionTaskStateRunning) {
  382. [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self];
  383. }
  384. }
  385. - (void)af_suspend {
  386. NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state");
  387. NSURLSessionTaskState state = [self state];
  388. [self af_suspend];
  389. if (state != NSURLSessionTaskStateSuspended) {
  390. [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self];
  391. }
  392. }
  393. @end
  394. #pragma mark -
  395. @interface AFURLSessionManager ()
  396. @property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration;
  397. @property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue;
  398. @property (readwrite, nonatomic, strong) NSURLSession *session;
  399. @property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier;
  400. @property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks;
  401. @property (readwrite, nonatomic, strong) NSLock *lock;
  402. @property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid;
  403. @property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge;
  404. @property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession;
  405. @property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection;
  406. @property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge;
  407. @property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream;
  408. @property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData;
  409. @property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete;
  410. @property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse;
  411. @property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask;
  412. @property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData;
  413. @property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse;
  414. @property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading;
  415. @property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData;
  416. @property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume;
  417. @end
  418. @implementation AFURLSessionManager
  419. - (instancetype)init {
  420. return [self initWithSessionConfiguration:nil];
  421. }
  422. - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration {
  423. self = [super init];
  424. if (!self) {
  425. return nil;
  426. }
  427. if (!configuration) {
  428. configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
  429. }
  430. self.sessionConfiguration = configuration;
  431. self.operationQueue = [[NSOperationQueue alloc] init];
  432. self.operationQueue.maxConcurrentOperationCount = 1;
  433. self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue];
  434. self.responseSerializer = [AFJSONResponseSerializer serializer];
  435. self.securityPolicy = [AFSecurityPolicy defaultPolicy];
  436. #if !TARGET_OS_WATCH
  437. self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
  438. #endif
  439. self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init];
  440. self.lock = [[NSLock alloc] init];
  441. self.lock.name = AFURLSessionManagerLockName;
  442. [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  443. for (NSURLSessionDataTask *task in dataTasks) {
  444. [self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil];
  445. }
  446. for (NSURLSessionUploadTask *uploadTask in uploadTasks) {
  447. [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil];
  448. }
  449. for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {
  450. [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil];
  451. }
  452. }];
  453. return self;
  454. }
  455. - (void)dealloc {
  456. [[NSNotificationCenter defaultCenter] removeObserver:self];
  457. }
  458. #pragma mark -
  459. - (NSString *)taskDescriptionForSessionTasks {
  460. return [NSString stringWithFormat:@"%p", self];
  461. }
  462. - (void)taskDidResume:(NSNotification *)notification {
  463. NSURLSessionTask *task = notification.object;
  464. if ([task respondsToSelector:@selector(taskDescription)]) {
  465. if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
  466. dispatch_async(dispatch_get_main_queue(), ^{
  467. [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task];
  468. });
  469. }
  470. }
  471. }
  472. - (void)taskDidSuspend:(NSNotification *)notification {
  473. NSURLSessionTask *task = notification.object;
  474. if ([task respondsToSelector:@selector(taskDescription)]) {
  475. if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) {
  476. dispatch_async(dispatch_get_main_queue(), ^{
  477. [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task];
  478. });
  479. }
  480. }
  481. }
  482. #pragma mark -
  483. - (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task {
  484. NSParameterAssert(task);
  485. AFURLSessionManagerTaskDelegate *delegate = nil;
  486. [self.lock lock];
  487. delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)];
  488. [self.lock unlock];
  489. return delegate;
  490. }
  491. - (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate
  492. forTask:(NSURLSessionTask *)task
  493. {
  494. NSParameterAssert(task);
  495. NSParameterAssert(delegate);
  496. [self.lock lock];
  497. self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate;
  498. [delegate setupProgressForTask:task];
  499. [self addNotificationObserverForTask:task];
  500. [self.lock unlock];
  501. }
  502. - (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask
  503. uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
  504. downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
  505. completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
  506. {
  507. AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
  508. delegate.manager = self;
  509. delegate.completionHandler = completionHandler;
  510. dataTask.taskDescription = self.taskDescriptionForSessionTasks;
  511. [self setDelegate:delegate forTask:dataTask];
  512. delegate.uploadProgressBlock = uploadProgressBlock;
  513. delegate.downloadProgressBlock = downloadProgressBlock;
  514. }
  515. - (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask
  516. progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
  517. completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
  518. {
  519. AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
  520. delegate.manager = self;
  521. delegate.completionHandler = completionHandler;
  522. uploadTask.taskDescription = self.taskDescriptionForSessionTasks;
  523. [self setDelegate:delegate forTask:uploadTask];
  524. delegate.uploadProgressBlock = uploadProgressBlock;
  525. }
  526. - (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask
  527. progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
  528. destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
  529. completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
  530. {
  531. AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init];
  532. delegate.manager = self;
  533. delegate.completionHandler = completionHandler;
  534. if (destination) {
  535. delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) {
  536. return destination(location, task.response);
  537. };
  538. }
  539. downloadTask.taskDescription = self.taskDescriptionForSessionTasks;
  540. [self setDelegate:delegate forTask:downloadTask];
  541. delegate.downloadProgressBlock = downloadProgressBlock;
  542. }
  543. - (void)removeDelegateForTask:(NSURLSessionTask *)task {
  544. NSParameterAssert(task);
  545. AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
  546. [self.lock lock];
  547. [delegate cleanUpProgressForTask:task];
  548. [self removeNotificationObserverForTask:task];
  549. [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)];
  550. [self.lock unlock];
  551. }
  552. #pragma mark -
  553. - (NSArray *)tasksForKeyPath:(NSString *)keyPath {
  554. __block NSArray *tasks = nil;
  555. dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
  556. [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  557. if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) {
  558. tasks = dataTasks;
  559. } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) {
  560. tasks = uploadTasks;
  561. } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) {
  562. tasks = downloadTasks;
  563. } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) {
  564. tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];
  565. }
  566. dispatch_semaphore_signal(semaphore);
  567. }];
  568. dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
  569. return tasks;
  570. }
  571. - (NSArray *)tasks {
  572. return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
  573. }
  574. - (NSArray *)dataTasks {
  575. return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
  576. }
  577. - (NSArray *)uploadTasks {
  578. return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
  579. }
  580. - (NSArray *)downloadTasks {
  581. return [self tasksForKeyPath:NSStringFromSelector(_cmd)];
  582. }
  583. #pragma mark -
  584. - (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks {
  585. dispatch_async(dispatch_get_main_queue(), ^{
  586. if (cancelPendingTasks) {
  587. [self.session invalidateAndCancel];
  588. } else {
  589. [self.session finishTasksAndInvalidate];
  590. }
  591. });
  592. }
  593. #pragma mark -
  594. - (void)setResponseSerializer:(id <AFURLResponseSerialization>)responseSerializer {
  595. NSParameterAssert(responseSerializer);
  596. _responseSerializer = responseSerializer;
  597. }
  598. #pragma mark -
  599. - (void)addNotificationObserverForTask:(NSURLSessionTask *)task {
  600. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task];
  601. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task];
  602. }
  603. - (void)removeNotificationObserverForTask:(NSURLSessionTask *)task {
  604. [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task];
  605. [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task];
  606. }
  607. #pragma mark -
  608. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
  609. completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
  610. {
  611. return [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler];
  612. }
  613. - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
  614. uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
  615. downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
  616. completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler {
  617. __block NSURLSessionDataTask *dataTask = nil;
  618. url_session_manager_create_task_safely(^{
  619. dataTask = [self.session dataTaskWithRequest:request];
  620. });
  621. [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];
  622. return dataTask;
  623. }
  624. #pragma mark -
  625. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
  626. fromFile:(NSURL *)fileURL
  627. progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
  628. completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
  629. {
  630. __block NSURLSessionUploadTask *uploadTask = nil;
  631. url_session_manager_create_task_safely(^{
  632. uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
  633. });
  634. if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) {
  635. for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) {
  636. uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
  637. }
  638. }
  639. [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler];
  640. return uploadTask;
  641. }
  642. - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
  643. fromData:(NSData *)bodyData
  644. progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
  645. completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
  646. {
  647. __block NSURLSessionUploadTask *uploadTask = nil;
  648. url_session_manager_create_task_safely(^{
  649. uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData];
  650. });
  651. [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler];
  652. return uploadTask;
  653. }
  654. - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
  655. progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
  656. completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
  657. {
  658. __block NSURLSessionUploadTask *uploadTask = nil;
  659. url_session_manager_create_task_safely(^{
  660. uploadTask = [self.session uploadTaskWithStreamedRequest:request];
  661. });
  662. [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler];
  663. return uploadTask;
  664. }
  665. #pragma mark -
  666. - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
  667. progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
  668. destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
  669. completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
  670. {
  671. __block NSURLSessionDownloadTask *downloadTask = nil;
  672. url_session_manager_create_task_safely(^{
  673. downloadTask = [self.session downloadTaskWithRequest:request];
  674. });
  675. [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
  676. return downloadTask;
  677. }
  678. - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
  679. progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock
  680. destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
  681. completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
  682. {
  683. __block NSURLSessionDownloadTask *downloadTask = nil;
  684. url_session_manager_create_task_safely(^{
  685. downloadTask = [self.session downloadTaskWithResumeData:resumeData];
  686. });
  687. [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler];
  688. return downloadTask;
  689. }
  690. #pragma mark -
  691. - (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task {
  692. return [[self delegateForTask:task] uploadProgress];
  693. }
  694. - (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task {
  695. return [[self delegateForTask:task] downloadProgress];
  696. }
  697. #pragma mark -
  698. - (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block {
  699. self.sessionDidBecomeInvalid = block;
  700. }
  701. - (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
  702. self.sessionDidReceiveAuthenticationChallenge = block;
  703. }
  704. - (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block {
  705. self.didFinishEventsForBackgroundURLSession = block;
  706. }
  707. #pragma mark -
  708. - (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block {
  709. self.taskNeedNewBodyStream = block;
  710. }
  711. - (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block {
  712. self.taskWillPerformHTTPRedirection = block;
  713. }
  714. - (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block {
  715. self.taskDidReceiveAuthenticationChallenge = block;
  716. }
  717. - (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block {
  718. self.taskDidSendBodyData = block;
  719. }
  720. - (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block {
  721. self.taskDidComplete = block;
  722. }
  723. #pragma mark -
  724. - (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block {
  725. self.dataTaskDidReceiveResponse = block;
  726. }
  727. - (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block {
  728. self.dataTaskDidBecomeDownloadTask = block;
  729. }
  730. - (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block {
  731. self.dataTaskDidReceiveData = block;
  732. }
  733. - (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block {
  734. self.dataTaskWillCacheResponse = block;
  735. }
  736. #pragma mark -
  737. - (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block {
  738. self.downloadTaskDidFinishDownloading = block;
  739. }
  740. - (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block {
  741. self.downloadTaskDidWriteData = block;
  742. }
  743. - (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block {
  744. self.downloadTaskDidResume = block;
  745. }
  746. #pragma mark - NSObject
  747. - (NSString *)description {
  748. return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue];
  749. }
  750. - (BOOL)respondsToSelector:(SEL)selector {
  751. if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) {
  752. return self.taskWillPerformHTTPRedirection != nil;
  753. } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
  754. return self.dataTaskDidReceiveResponse != nil;
  755. } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) {
  756. return self.dataTaskWillCacheResponse != nil;
  757. } else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) {
  758. return self.didFinishEventsForBackgroundURLSession != nil;
  759. }
  760. return [[self class] instancesRespondToSelector:selector];
  761. }
  762. #pragma mark - NSURLSessionDelegate
  763. - (void)URLSession:(NSURLSession *)session
  764. didBecomeInvalidWithError:(NSError *)error
  765. {
  766. if (self.sessionDidBecomeInvalid) {
  767. self.sessionDidBecomeInvalid(session, error);
  768. }
  769. [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session];
  770. }
  771. - (void)URLSession:(NSURLSession *)session
  772. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  773. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  774. {
  775. NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  776. __block NSURLCredential *credential = nil;
  777. if (self.sessionDidReceiveAuthenticationChallenge) {
  778. disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential);
  779. } else {
  780. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  781. if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
  782. credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  783. if (credential) {
  784. disposition = NSURLSessionAuthChallengeUseCredential;
  785. } else {
  786. disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  787. }
  788. } else {
  789. disposition = NSURLSessionAuthChallengeRejectProtectionSpace;
  790. }
  791. } else {
  792. disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  793. }
  794. }
  795. if (completionHandler) {
  796. completionHandler(disposition, credential);
  797. }
  798. }
  799. #pragma mark - NSURLSessionTaskDelegate
  800. - (void)URLSession:(NSURLSession *)session
  801. task:(NSURLSessionTask *)task
  802. willPerformHTTPRedirection:(NSHTTPURLResponse *)response
  803. newRequest:(NSURLRequest *)request
  804. completionHandler:(void (^)(NSURLRequest *))completionHandler
  805. {
  806. NSURLRequest *redirectRequest = request;
  807. if (self.taskWillPerformHTTPRedirection) {
  808. redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request);
  809. }
  810. if (completionHandler) {
  811. completionHandler(redirectRequest);
  812. }
  813. }
  814. - (void)URLSession:(NSURLSession *)session
  815. task:(NSURLSessionTask *)task
  816. didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
  817. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
  818. {
  819. NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  820. __block NSURLCredential *credential = nil;
  821. if (self.taskDidReceiveAuthenticationChallenge) {
  822. disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential);
  823. } else {
  824. if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
  825. if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
  826. disposition = NSURLSessionAuthChallengeUseCredential;
  827. credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
  828. } else {
  829. disposition = NSURLSessionAuthChallengeRejectProtectionSpace;
  830. }
  831. } else {
  832. disposition = NSURLSessionAuthChallengePerformDefaultHandling;
  833. }
  834. }
  835. if (completionHandler) {
  836. completionHandler(disposition, credential);
  837. }
  838. }
  839. - (void)URLSession:(NSURLSession *)session
  840. task:(NSURLSessionTask *)task
  841. needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler
  842. {
  843. NSInputStream *inputStream = nil;
  844. if (self.taskNeedNewBodyStream) {
  845. inputStream = self.taskNeedNewBodyStream(session, task);
  846. } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) {
  847. inputStream = [task.originalRequest.HTTPBodyStream copy];
  848. }
  849. if (completionHandler) {
  850. completionHandler(inputStream);
  851. }
  852. }
  853. - (void)URLSession:(NSURLSession *)session
  854. task:(NSURLSessionTask *)task
  855. didSendBodyData:(int64_t)bytesSent
  856. totalBytesSent:(int64_t)totalBytesSent
  857. totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
  858. {
  859. int64_t totalUnitCount = totalBytesExpectedToSend;
  860. if(totalUnitCount == NSURLSessionTransferSizeUnknown) {
  861. NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"];
  862. if(contentLength) {
  863. totalUnitCount = (int64_t) [contentLength longLongValue];
  864. }
  865. }
  866. if (self.taskDidSendBodyData) {
  867. self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount);
  868. }
  869. }
  870. - (void)URLSession:(NSURLSession *)session
  871. task:(NSURLSessionTask *)task
  872. didCompleteWithError:(NSError *)error
  873. {
  874. AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
  875. // delegate may be nil when completing a task in the background
  876. if (delegate) {
  877. [delegate URLSession:session task:task didCompleteWithError:error];
  878. [self removeDelegateForTask:task];
  879. }
  880. if (self.taskDidComplete) {
  881. self.taskDidComplete(session, task, error);
  882. }
  883. }
  884. #pragma mark - NSURLSessionDataDelegate
  885. - (void)URLSession:(NSURLSession *)session
  886. dataTask:(NSURLSessionDataTask *)dataTask
  887. didReceiveResponse:(NSURLResponse *)response
  888. completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
  889. {
  890. NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow;
  891. if (self.dataTaskDidReceiveResponse) {
  892. disposition = self.dataTaskDidReceiveResponse(session, dataTask, response);
  893. }
  894. if (completionHandler) {
  895. completionHandler(disposition);
  896. }
  897. }
  898. - (void)URLSession:(NSURLSession *)session
  899. dataTask:(NSURLSessionDataTask *)dataTask
  900. didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask
  901. {
  902. AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
  903. if (delegate) {
  904. [self removeDelegateForTask:dataTask];
  905. [self setDelegate:delegate forTask:downloadTask];
  906. }
  907. if (self.dataTaskDidBecomeDownloadTask) {
  908. self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask);
  909. }
  910. }
  911. - (void)URLSession:(NSURLSession *)session
  912. dataTask:(NSURLSessionDataTask *)dataTask
  913. didReceiveData:(NSData *)data
  914. {
  915. AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask];
  916. [delegate URLSession:session dataTask:dataTask didReceiveData:data];
  917. if (self.dataTaskDidReceiveData) {
  918. self.dataTaskDidReceiveData(session, dataTask, data);
  919. }
  920. }
  921. - (void)URLSession:(NSURLSession *)session
  922. dataTask:(NSURLSessionDataTask *)dataTask
  923. willCacheResponse:(NSCachedURLResponse *)proposedResponse
  924. completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler
  925. {
  926. NSCachedURLResponse *cachedResponse = proposedResponse;
  927. if (self.dataTaskWillCacheResponse) {
  928. cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse);
  929. }
  930. if (completionHandler) {
  931. completionHandler(cachedResponse);
  932. }
  933. }
  934. - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
  935. if (self.didFinishEventsForBackgroundURLSession) {
  936. dispatch_async(dispatch_get_main_queue(), ^{
  937. self.didFinishEventsForBackgroundURLSession(session);
  938. });
  939. }
  940. }
  941. #pragma mark - NSURLSessionDownloadDelegate
  942. - (void)URLSession:(NSURLSession *)session
  943. downloadTask:(NSURLSessionDownloadTask *)downloadTask
  944. didFinishDownloadingToURL:(NSURL *)location
  945. {
  946. AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
  947. if (self.downloadTaskDidFinishDownloading) {
  948. NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
  949. if (fileURL) {
  950. delegate.downloadFileURL = fileURL;
  951. NSError *error = nil;
  952. [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error];
  953. if (error) {
  954. [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo];
  955. }
  956. return;
  957. }
  958. }
  959. if (delegate) {
  960. [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location];
  961. }
  962. }
  963. - (void)URLSession:(NSURLSession *)session
  964. downloadTask:(NSURLSessionDownloadTask *)downloadTask
  965. didWriteData:(int64_t)bytesWritten
  966. totalBytesWritten:(int64_t)totalBytesWritten
  967. totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
  968. {
  969. if (self.downloadTaskDidWriteData) {
  970. self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  971. }
  972. }
  973. - (void)URLSession:(NSURLSession *)session
  974. downloadTask:(NSURLSessionDownloadTask *)downloadTask
  975. didResumeAtOffset:(int64_t)fileOffset
  976. expectedTotalBytes:(int64_t)expectedTotalBytes
  977. {
  978. if (self.downloadTaskDidResume) {
  979. self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes);
  980. }
  981. }
  982. #pragma mark - NSSecureCoding
  983. + (BOOL)supportsSecureCoding {
  984. return YES;
  985. }
  986. - (instancetype)initWithCoder:(NSCoder *)decoder {
  987. NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
  988. self = [self initWithSessionConfiguration:configuration];
  989. if (!self) {
  990. return nil;
  991. }
  992. return self;
  993. }
  994. - (void)encodeWithCoder:(NSCoder *)coder {
  995. [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
  996. }
  997. #pragma mark - NSCopying
  998. - (instancetype)copyWithZone:(NSZone *)zone {
  999. return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration];
  1000. }
  1001. @end