PageRenderTime 61ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 1ms

/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m

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