AFURLSessionManager.m 49 KB

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