AFURLSessionManager.m 53 KB

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