FLEXNetworkObserver.m 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. //
  2. // FLEXNetworkObserver.m
  3. // Derived from:
  4. //
  5. // PDAFNetworkDomainController.m
  6. // PonyDebugger
  7. //
  8. // Created by Mike Lewis on 2/27/12.
  9. //
  10. // Licensed to Square, Inc. under one or more contributor license agreements.
  11. // See the LICENSE file distributed with this work for the terms under
  12. // which Square, Inc. licenses this file to you.
  13. //
  14. #import "FLEXNetworkObserver.h"
  15. #import "FLEXNetworkRecorder.h"
  16. #import <objc/runtime.h>
  17. #import <objc/message.h>
  18. #import <dispatch/queue.h>
  19. NSString *const kFLEXNetworkObserverEnabledStateChangedNotification = @"kFLEXNetworkObserverEnabledStateChangedNotification";
  20. static NSString *const kFLEXNetworkObserverEnableOnLaunchDefaultsKey = @"com.flex.FLEXNetworkObserver.enableOnLaunch";
  21. @interface FLEXInternalRequestState : NSObject
  22. @property (nonatomic, copy) NSURLRequest *request;
  23. @property (nonatomic, strong) NSMutableData *dataAccumulator;
  24. @property (nonatomic, copy) NSString *requestID;
  25. @end
  26. @implementation FLEXInternalRequestState
  27. @end
  28. @interface FLEXNetworkObserver (NSURLConnectionHelpers)
  29. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id <NSURLConnectionDelegate>)delegate;
  30. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id <NSURLConnectionDelegate>)delegate;
  31. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id <NSURLConnectionDelegate>)delegate;
  32. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id <NSURLConnectionDelegate>)delegate;
  33. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id <NSURLConnectionDelegate>)delegate;
  34. @end
  35. @interface FLEXNetworkObserver (NSURLSessionTaskHelpers)
  36. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id <NSURLSessionDelegate>)delegate;
  37. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id <NSURLSessionDelegate>)delegate;
  38. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id <NSURLSessionDelegate>)delegate;
  39. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id <NSURLSessionDelegate>)delegate;
  40. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id <NSURLSessionDelegate>)delegate;
  41. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id <NSURLSessionDelegate>)delegate;
  42. @end
  43. @interface FLEXNetworkObserver ()
  44. @property (nonatomic, assign, getter=isEnabled) BOOL enabled;
  45. @property (nonatomic, strong) NSMutableDictionary *connectionStates;
  46. @property (nonatomic, strong) dispatch_queue_t queue;
  47. @end
  48. @implementation FLEXNetworkObserver
  49. #pragma mark - Public Methods
  50. + (void)setEnabled:(BOOL)enabled
  51. {
  52. if (enabled) {
  53. // Inject if needed. This injection is protected with a dispatch_once, so we're ok calling it multiple times.
  54. // By doing the injection lazily, we keep the impact of the tool lower when this feature isn't enabled.
  55. [self injectIntoAllNSURLConnectionDelegateClasses];
  56. }
  57. [[self sharedObserver] setEnabled:enabled];
  58. }
  59. + (BOOL)isEnabled
  60. {
  61. return [[self sharedObserver] isEnabled];
  62. }
  63. - (void)setEnabled:(BOOL)enabled
  64. {
  65. if (_enabled != enabled) {
  66. _enabled = enabled;
  67. [[NSNotificationCenter defaultCenter] postNotificationName:kFLEXNetworkObserverEnabledStateChangedNotification object:self];
  68. }
  69. }
  70. + (void)setShouldEnableOnLaunch:(BOOL)shouldEnableOnLaunch
  71. {
  72. [[NSUserDefaults standardUserDefaults] setObject:@YES forKey:kFLEXNetworkObserverEnableOnLaunchDefaultsKey];
  73. }
  74. + (BOOL)shouldEnableOnLaunch
  75. {
  76. return [[[NSUserDefaults standardUserDefaults] objectForKey:kFLEXNetworkObserverEnableOnLaunchDefaultsKey] boolValue];
  77. }
  78. + (void)load
  79. {
  80. // We don't want to do the swizzling from +load because not all the classes may be loaded at this point.
  81. dispatch_async(dispatch_get_main_queue(), ^{
  82. if ([self shouldEnableOnLaunch]) {
  83. [self setEnabled:YES];
  84. }
  85. });
  86. }
  87. #pragma mark - Statics
  88. + (instancetype)sharedObserver
  89. {
  90. static FLEXNetworkObserver *sharedObserver = nil;
  91. static dispatch_once_t onceToken;
  92. dispatch_once(&onceToken, ^{
  93. sharedObserver = [[[self class] alloc] init];
  94. });
  95. return sharedObserver;
  96. }
  97. + (NSString *)nextRequestID
  98. {
  99. static NSInteger sequenceNumber = 0;
  100. static NSString *seed = nil;
  101. static dispatch_once_t onceToken;
  102. dispatch_once(&onceToken, ^{
  103. CFUUIDRef uuid = CFUUIDCreate(CFAllocatorGetDefault());
  104. seed = (__bridge NSString *)CFUUIDCreateString(CFAllocatorGetDefault(), uuid);
  105. CFRelease(uuid);
  106. });
  107. return [[NSString alloc] initWithFormat:@"%@-%ld", seed, (long)(++sequenceNumber)];
  108. }
  109. #pragma mark Delegate Injection Convenience Methods
  110. + (SEL)swizzledSelectorForSelector:(SEL)selector
  111. {
  112. return NSSelectorFromString([NSString stringWithFormat:@"_flex_swizzle_%x_%@", arc4random(), NSStringFromSelector(selector)]);
  113. }
  114. /// All swizzled delegate methods should make use of this guard.
  115. /// This will prevent duplicated sniffing when the original implementation calls up to a superclass implementation which we've also swizzled.
  116. /// The superclass implementation (and implementations in classes above that) will be executed without inteference if called from the original implementation.
  117. + (void)sniffWithoutDuplicationForObject:(NSObject *)object selector:(SEL)selector sniffingBlock:(void (^)(void))sniffingBlock originalImplementationBlock:(void (^)(void))originalImplementationBlock
  118. {
  119. const void *key = selector;
  120. // Don't run the sniffing block if we're inside a nested call
  121. if (!objc_getAssociatedObject(object, key)) {
  122. sniffingBlock();
  123. }
  124. // Mark that we're calling through to the original so we can detect nested calls
  125. objc_setAssociatedObject(object, key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  126. originalImplementationBlock();
  127. objc_setAssociatedObject(object, key, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  128. }
  129. + (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls
  130. {
  131. if ([cls instancesRespondToSelector:selector]) {
  132. unsigned int numMethods = 0;
  133. Method *methods = class_copyMethodList(cls, &numMethods);
  134. BOOL implementsSelector = NO;
  135. for (int index = 0; index < numMethods; index++) {
  136. SEL methodSelector = method_getName(methods[index]);
  137. if (selector == methodSelector) {
  138. implementsSelector = YES;
  139. break;
  140. }
  141. }
  142. free(methods);
  143. if (!implementsSelector) {
  144. return YES;
  145. }
  146. }
  147. return NO;
  148. }
  149. + (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock
  150. {
  151. if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) {
  152. return;
  153. }
  154. IMP implementation = imp_implementationWithBlock((id)([cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock));
  155. Method oldMethod = class_getInstanceMethod(cls, selector);
  156. if (oldMethod) {
  157. class_addMethod(cls, swizzledSelector, implementation, methodDescription.types);
  158. Method newMethod = class_getInstanceMethod(cls, swizzledSelector);
  159. method_exchangeImplementations(oldMethod, newMethod);
  160. } else {
  161. class_addMethod(cls, selector, implementation, methodDescription.types);
  162. }
  163. }
  164. #pragma mark - Delegate Injection
  165. + (void)injectIntoAllNSURLConnectionDelegateClasses
  166. {
  167. // Only allow swizzling once.
  168. static dispatch_once_t onceToken;
  169. dispatch_once(&onceToken, ^{
  170. // Swizzle any classes that implement one of these selectors.
  171. const SEL selectors[] = {
  172. @selector(connectionDidFinishLoading:),
  173. @selector(connection:didReceiveResponse:),
  174. @selector(URLSession:dataTask:didReceiveResponse:completionHandler:),
  175. @selector(URLSession:task:didCompleteWithError:),
  176. @selector(URLSession:downloadTask:didFinishDownloadingToURL:)
  177. };
  178. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  179. Class *classes = NULL;
  180. int numClasses = objc_getClassList(NULL, 0);
  181. if (numClasses > 0) {
  182. classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
  183. numClasses = objc_getClassList(classes, numClasses);
  184. for (NSInteger classIndex = 0; classIndex < numClasses; ++classIndex) {
  185. Class class = classes[classIndex];
  186. if (class == [FLEXNetworkObserver class]) {
  187. continue;
  188. }
  189. // Use the runtime API rather than the methods on NSObject to avoid sending messages to
  190. // classes we're not interested in swizzling. Otherwise we hit +initialize on all classes.
  191. for (int selectorIndex = 0; selectorIndex < numSelectors; ++selectorIndex) {
  192. if (class_getInstanceMethod(class, selectors[selectorIndex])) {
  193. [self injectIntoDelegateClass:class];
  194. break;
  195. }
  196. }
  197. }
  198. free(classes);
  199. }
  200. });
  201. }
  202. + (void)injectIntoDelegateClass:(Class)cls
  203. {
  204. // Connections
  205. [self injectWillSendRequestIntoDelegateClass:cls];
  206. [self injectDidReceiveDataIntoDelegateClass:cls];
  207. [self injectDidReceiveResponseIntoDelegateClass:cls];
  208. [self injectDidFinishLoadingIntoDelegateClass:cls];
  209. [self injectDidFailWithErrorIntoDelegateClass:cls];
  210. // Sessions
  211. [self injectTaskWillPerformHTTPRedirectionIntoDelegateClass:cls];
  212. [self injectTaskDidReceiveDataIntoDelegateClass:cls];
  213. [self injectTaskDidReceiveResponseIntoDelegateClass:cls];
  214. [self injectTaskDidCompleteWithErrorIntoDelegateClass:cls];
  215. [self injectRespondsToSelectorIntoDelegateClass:cls];
  216. // Download tasks
  217. [self injectDownloadTaskDidWriteDataIntoDelegateClass:cls];
  218. [self injectDownloadTaskDidFinishDownloadingIntoDelegateClass:cls];
  219. }
  220. + (void)injectWillSendRequestIntoDelegateClass:(Class)cls
  221. {
  222. SEL selector = @selector(connection:willSendRequest:redirectResponse:);
  223. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  224. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  225. if (!protocol) {
  226. protocol = @protocol(NSURLConnectionDelegate);
  227. }
  228. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  229. typedef NSURLRequest *(^NSURLConnectionWillSendRequestBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response);
  230. NSURLConnectionWillSendRequestBlock undefinedBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  231. [[FLEXNetworkObserver sharedObserver] connection:connection willSendRequest:request redirectResponse:response delegate:slf];
  232. return request;
  233. };
  234. NSURLConnectionWillSendRequestBlock implementationBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  235. __block NSURLRequest *returnValue = nil;
  236. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  237. undefinedBlock(slf, connection, request, response);
  238. } originalImplementationBlock:^{
  239. returnValue = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, connection, request, response);
  240. }];
  241. return returnValue;
  242. };
  243. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  244. }
  245. + (void)injectDidReceiveResponseIntoDelegateClass:(Class)cls
  246. {
  247. SEL selector = @selector(connection:didReceiveResponse:);
  248. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  249. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  250. if (!protocol) {
  251. protocol = @protocol(NSURLConnectionDelegate);
  252. }
  253. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  254. typedef void (^NSURLConnectionDidReceiveResponseBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response);
  255. NSURLConnectionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  256. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveResponse:response delegate:slf];
  257. };
  258. NSURLConnectionDidReceiveResponseBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  259. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  260. undefinedBlock(slf, connection, response);
  261. } originalImplementationBlock:^{
  262. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, response);
  263. }];
  264. };
  265. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  266. }
  267. + (void)injectDidReceiveDataIntoDelegateClass:(Class)cls
  268. {
  269. SEL selector = @selector(connection:didReceiveData:);
  270. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  271. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  272. if (!protocol) {
  273. protocol = @protocol(NSURLConnectionDelegate);
  274. }
  275. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  276. typedef void (^NSURLConnectionDidReceiveDataBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data);
  277. NSURLConnectionDidReceiveDataBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  278. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveData:data delegate:slf];
  279. };
  280. NSURLConnectionDidReceiveDataBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  281. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  282. undefinedBlock(slf, connection, data);
  283. } originalImplementationBlock:^{
  284. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, data);
  285. }];
  286. };
  287. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  288. }
  289. + (void)injectDidFinishLoadingIntoDelegateClass:(Class)cls
  290. {
  291. SEL selector = @selector(connectionDidFinishLoading:);
  292. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  293. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  294. if (!protocol) {
  295. protocol = @protocol(NSURLConnectionDelegate);
  296. }
  297. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  298. typedef void (^NSURLConnectionDidFinishLoadingBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection);
  299. NSURLConnectionDidFinishLoadingBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  300. [[FLEXNetworkObserver sharedObserver] connectionDidFinishLoading:connection delegate:slf];
  301. };
  302. NSURLConnectionDidFinishLoadingBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  303. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  304. undefinedBlock(slf, connection);
  305. } originalImplementationBlock:^{
  306. ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSelector, connection);
  307. }];
  308. };
  309. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  310. }
  311. + (void)injectDidFailWithErrorIntoDelegateClass:(Class)cls
  312. {
  313. SEL selector = @selector(connection:didFailWithError:);
  314. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  315. Protocol *protocol = @protocol(NSURLConnectionDelegate);
  316. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  317. typedef void (^NSURLConnectionDidFailWithErrorBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error);
  318. NSURLConnectionDidFailWithErrorBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  319. [[FLEXNetworkObserver sharedObserver] connection:connection didFailWithError:error delegate:slf];
  320. };
  321. NSURLConnectionDidFailWithErrorBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  322. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  323. undefinedBlock(slf, connection, error);
  324. } originalImplementationBlock:^{
  325. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, error);
  326. }];
  327. };
  328. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  329. }
  330. + (void)injectTaskWillPerformHTTPRedirectionIntoDelegateClass:(Class)cls
  331. {
  332. SEL selector = @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:);
  333. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  334. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  335. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  336. typedef void (^NSURLSessionWillPerformHTTPRedirectionBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *));
  337. NSURLSessionWillPerformHTTPRedirectionBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  338. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task willPerformHTTPRedirection:response newRequest:newRequest completionHandler:completionHandler delegate:slf];
  339. };
  340. NSURLSessionWillPerformHTTPRedirectionBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  341. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  342. undefinedBlock(slf, session, task, response, newRequest, completionHandler);
  343. } originalImplementationBlock:^{
  344. ((id(*)(id, SEL, id, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, task, response, newRequest, completionHandler);
  345. }];
  346. };
  347. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  348. }
  349. + (void)injectTaskDidReceiveDataIntoDelegateClass:(Class)cls
  350. {
  351. SEL selector = @selector(URLSession:dataTask:didReceiveData:);
  352. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  353. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  354. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  355. typedef void (^NSURLSessionDidReceiveDataBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
  356. NSURLSessionDidReceiveDataBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  357. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveData:data delegate:slf];
  358. };
  359. NSURLSessionDidReceiveDataBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  360. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  361. undefinedBlock(slf, session, dataTask, data);
  362. } originalImplementationBlock:^{
  363. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, data);
  364. }];
  365. };
  366. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  367. }
  368. + (void)injectTaskDidReceiveResponseIntoDelegateClass:(Class)cls
  369. {
  370. SEL selector = @selector(URLSession:dataTask:didReceiveResponse:completionHandler:);
  371. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  372. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  373. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  374. typedef void (^NSURLSessionDidReceiveResponseBlock)(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition));
  375. NSURLSessionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  376. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler delegate:slf];
  377. };
  378. NSURLSessionDidReceiveResponseBlock implementationBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  379. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  380. undefinedBlock(slf, session, dataTask, response, completionHandler);
  381. } originalImplementationBlock:^{
  382. ((void(*)(id, SEL, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, dataTask, response, completionHandler);
  383. }];
  384. };
  385. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  386. }
  387. + (void)injectTaskDidCompleteWithErrorIntoDelegateClass:(Class)cls
  388. {
  389. SEL selector = @selector(URLSession:task:didCompleteWithError:);
  390. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  391. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  392. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  393. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error);
  394. NSURLSessionTaskDidCompleteWithErrorBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  395. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didCompleteWithError:error delegate:slf];
  396. };
  397. NSURLSessionTaskDidCompleteWithErrorBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  398. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  399. undefinedBlock(slf, session, task, error);
  400. } originalImplementationBlock:^{
  401. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, error);
  402. }];
  403. };
  404. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  405. }
  406. // Used for overriding AFNetworking behavior
  407. + (void)injectRespondsToSelectorIntoDelegateClass:(Class)cls
  408. {
  409. SEL selector = @selector(respondsToSelector:);
  410. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  411. //Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  412. Method method = class_getInstanceMethod(cls, selector);
  413. struct objc_method_description methodDescription = *method_getDescription(method);
  414. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id slf, SEL sel);
  415. BOOL (^undefinedBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id slf, SEL sel) {
  416. return YES;
  417. };
  418. BOOL (^implementationBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id <NSURLSessionTaskDelegate> slf, SEL sel) {
  419. if (sel == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
  420. return undefinedBlock(slf, sel);
  421. }
  422. return ((BOOL(*)(id, SEL, SEL))objc_msgSend)(slf, swizzledSelector, sel);
  423. };
  424. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  425. }
  426. + (void)injectDownloadTaskDidFinishDownloadingIntoDelegateClass:(Class)cls
  427. {
  428. SEL selector = @selector(URLSession:downloadTask:didFinishDownloadingToURL:);
  429. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  430. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  431. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  432. typedef void (^NSURLSessionDownloadTaskDidFinishDownloadingBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location);
  433. NSURLSessionDownloadTaskDidFinishDownloadingBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  434. NSData *data = [NSData dataWithContentsOfFile:location.relativePath];
  435. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didFinishDownloadingToURL:location data:data delegate:slf];
  436. };
  437. NSURLSessionDownloadTaskDidFinishDownloadingBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  438. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  439. undefinedBlock(slf, session, task, location);
  440. } originalImplementationBlock:^{
  441. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, location);
  442. }];
  443. };
  444. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  445. }
  446. + (void)injectDownloadTaskDidWriteDataIntoDelegateClass:(Class)cls
  447. {
  448. SEL selector = @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:);
  449. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  450. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  451. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  452. typedef void (^NSURLSessionDownloadTaskDidWriteDataBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
  453. NSURLSessionDownloadTaskDidWriteDataBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  454. [[FLEXNetworkObserver sharedObserver] URLSession:session downloadTask:task didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite delegate:slf];
  455. };
  456. NSURLSessionDownloadTaskDidWriteDataBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  457. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  458. undefinedBlock(slf, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  459. } originalImplementationBlock:^{
  460. ((void(*)(id, SEL, id, id, int64_t, int64_t, int64_t))objc_msgSend)(slf, swizzledSelector, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  461. }];
  462. };
  463. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  464. }
  465. #pragma mark - Initialization
  466. - (id)init
  467. {
  468. self = [super init];
  469. if (!self) {
  470. return nil;
  471. }
  472. _connectionStates = [[NSMutableDictionary alloc] init];
  473. _queue = dispatch_queue_create("com.flex.FLEXNetworkObserver", DISPATCH_QUEUE_SERIAL);
  474. return self;
  475. }
  476. #pragma mark - Private Methods
  477. - (void)performBlock:(dispatch_block_t)block
  478. {
  479. if (self.isEnabled) {
  480. dispatch_async(_queue, block);
  481. }
  482. }
  483. #pragma mark - Private Methods (Connections)
  484. - (FLEXInternalRequestState *)requestStateForConnection:(NSURLConnection *)connection
  485. {
  486. NSValue *key = [NSValue valueWithNonretainedObject:connection];
  487. FLEXInternalRequestState *state = [_connectionStates objectForKey:key];
  488. if (!state) {
  489. state = [[FLEXInternalRequestState alloc] init];
  490. state.requestID = [[self class] nextRequestID];
  491. [_connectionStates setObject:state forKey:key];
  492. }
  493. return state;
  494. }
  495. - (NSString *)requestIDForConnection:(NSURLConnection *)connection
  496. {
  497. return [self requestStateForConnection:connection].requestID;
  498. }
  499. - (void)setRequest:(NSURLRequest *)request forConnection:(NSURLConnection *)connection
  500. {
  501. [self requestStateForConnection:connection].request = request;
  502. }
  503. - (NSURLRequest *)requestForConnection:(NSURLConnection *)connection
  504. {
  505. return [self requestStateForConnection:connection].request;
  506. }
  507. - (void)setAccumulatedData:(NSMutableData *)data forConnection:(NSURLConnection *)connection
  508. {
  509. FLEXInternalRequestState *requestState = [self requestStateForConnection:connection];
  510. requestState.dataAccumulator = data;
  511. }
  512. - (void)addAccumulatedData:(NSData *)data forConnection:(NSURLConnection *)connection
  513. {
  514. NSMutableData *dataAccumulator = [self requestStateForConnection:connection].dataAccumulator;
  515. [dataAccumulator appendData:data];
  516. }
  517. - (NSData *)accumulatedDataForConnection:(NSURLConnection *)connection
  518. {
  519. return [self requestStateForConnection:connection].dataAccumulator;
  520. }
  521. // This removes storing the accumulated request/response from the dictionary so we can release connection
  522. - (void)connectionFinished:(NSURLConnection *)connection
  523. {
  524. NSValue *key = [NSValue valueWithNonretainedObject:connection];
  525. [_connectionStates removeObjectForKey:key];
  526. }
  527. #pragma mark - Private Methods (Tasks)
  528. - (FLEXInternalRequestState *)requestStateForTask:(NSURLSessionTask *)task
  529. {
  530. NSValue *key = [NSValue valueWithNonretainedObject:task];
  531. FLEXInternalRequestState *state = [_connectionStates objectForKey:key];
  532. if (!state) {
  533. state = [[FLEXInternalRequestState alloc] init];
  534. state.requestID = [[self class] nextRequestID];
  535. [_connectionStates setObject:state forKey:key];
  536. }
  537. return state;
  538. }
  539. - (NSString *)requestIDForTask:(NSURLSessionTask *)task
  540. {
  541. return [self requestStateForTask:task].requestID;
  542. }
  543. - (void)setRequest:(NSURLRequest *)request forTask:(NSURLSessionTask *)task
  544. {
  545. [self requestStateForTask:task].request = request;
  546. }
  547. - (NSURLRequest *)requestForTask:(NSURLSessionTask *)task
  548. {
  549. return [self requestStateForTask:task].request;
  550. }
  551. - (void)setAccumulatedData:(NSMutableData *)data forTask:(NSURLSessionTask *)task
  552. {
  553. FLEXInternalRequestState *requestState = [self requestStateForTask:task];
  554. requestState.dataAccumulator = data;
  555. }
  556. - (void)addAccumulatedData:(NSData *)data forTask:(NSURLSessionTask *)task
  557. {
  558. NSMutableData *dataAccumulator = [self requestStateForTask:task].dataAccumulator;
  559. [dataAccumulator appendData:data];
  560. }
  561. - (NSData *)accumulatedDataForTask:(NSURLSessionTask *)task
  562. {
  563. return [self requestStateForTask:task].dataAccumulator;
  564. }
  565. // This removes storing the accumulated request/response from the dictionary so we can release task
  566. - (void)taskFinished:(NSURLSessionTask *)task
  567. {
  568. NSValue *key = [NSValue valueWithNonretainedObject:task];
  569. [_connectionStates removeObjectForKey:key];
  570. }
  571. @end
  572. @implementation FLEXNetworkObserver (NSURLConnectionHelpers)
  573. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  574. {
  575. [self performBlock:^{
  576. [self setRequest:request forConnection:connection];
  577. NSString *requestId = [self requestIDForConnection:connection];
  578. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestId request:request redirectResponse:response requestMechanism:[NSString stringWithFormat:@"NSURLConnection (%@)", [delegate class]]];
  579. }];
  580. }
  581. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  582. {
  583. [self performBlock:^{
  584. // If the request wasn't generated yet, then willSendRequest was not called. This appears to be an inconsistency in documentation
  585. // and behavior.
  586. NSURLRequest *request = [self requestForConnection:connection];
  587. if (!request) {
  588. request = connection.currentRequest;
  589. [self setRequest:request forConnection:connection];
  590. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForConnection:connection] request:request redirectResponse:nil requestMechanism:[NSString stringWithFormat:@"NSURLConnection (delegate: %@)", [delegate class]]];
  591. }
  592. NSMutableData *dataAccumulator = nil;
  593. if (response.expectedContentLength < 0) {
  594. dataAccumulator = [[NSMutableData alloc] init];
  595. } else {
  596. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  597. }
  598. [self setAccumulatedData:dataAccumulator forConnection:connection];
  599. NSString *requestID = [self requestIDForConnection:connection];
  600. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID request:connection.currentRequest response:response];
  601. }];
  602. }
  603. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id<NSURLConnectionDelegate>)delegate
  604. {
  605. // Just to be safe since we're doing this async
  606. data = [data copy];
  607. [self performBlock:^{
  608. [self addAccumulatedData:data forConnection:connection];
  609. if ([self accumulatedDataForConnection:connection] == nil) return;
  610. NSString *requestID = [self requestIDForConnection:connection];
  611. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID request:connection.currentRequest dataLength:data.length];
  612. }];
  613. }
  614. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id<NSURLConnectionDelegate>)delegate
  615. {
  616. [self performBlock:^{
  617. NSString *requestID = [self requestIDForConnection:connection];
  618. NSData *accumulatedData = [self accumulatedDataForConnection:connection];
  619. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID request:connection.currentRequest responseBody:accumulatedData];
  620. [self connectionFinished:connection];
  621. }];
  622. }
  623. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id<NSURLConnectionDelegate>)delegate
  624. {
  625. [self performBlock:^{
  626. NSString *requestID = [self requestIDForConnection:connection];
  627. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestId:requestID request:connection.currentRequest error:error];
  628. [self connectionFinished:connection];
  629. }];
  630. }
  631. @end
  632. @implementation FLEXNetworkObserver (NSURLSessionTaskHelpers)
  633. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  634. {
  635. [self performBlock:^{
  636. [self setRequest:request forTask:task];
  637. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForTask:task] request:request redirectResponse:response requestMechanism:[NSString stringWithFormat:@"NSURLSessionTask (delegate: %@)", [delegate class]]];
  638. }];
  639. }
  640. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  641. {
  642. // willSendRequest does not exist in NSURLSession. Here's a workaround.
  643. NSURLRequest *request = [self requestForTask:dataTask];
  644. if (!request) {
  645. request = dataTask.currentRequest;
  646. [self setRequest:request forTask:dataTask];
  647. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForTask:dataTask] request:request redirectResponse:nil requestMechanism:[NSString stringWithFormat:@"NSURLSessionDataTask (delegate: %@)", [delegate class]]];
  648. }
  649. NSMutableData *dataAccumulator = nil;
  650. if (response.expectedContentLength < 0) {
  651. dataAccumulator = [[NSMutableData alloc] init];
  652. } else {
  653. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  654. }
  655. [self setAccumulatedData:dataAccumulator forTask:dataTask];
  656. NSString *requestID = [self requestIDForTask:dataTask];
  657. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID request:dataTask.currentRequest response:response];
  658. }
  659. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  660. {
  661. // Just to be safe since we're doing this async
  662. data = [data copy];
  663. [self performBlock:^{
  664. [self addAccumulatedData:data forTask:dataTask];
  665. if ([self accumulatedDataForTask:dataTask] == nil) return;
  666. NSString *requestID = [self requestIDForTask:dataTask];
  667. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID request:dataTask.currentRequest dataLength:data.length];
  668. }];
  669. }
  670. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id<NSURLSessionDelegate>)delegate
  671. {
  672. [self performBlock:^{
  673. NSString *requestID = [self requestIDForTask:task];
  674. NSData *accumulatedData = [self accumulatedDataForTask:task];
  675. if (error) {
  676. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestId:requestID request:task.currentRequest error:error];
  677. } else {
  678. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID request:task.currentRequest responseBody:accumulatedData];
  679. }
  680. [self taskFinished:task];
  681. }];
  682. }
  683. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id<NSURLSessionDelegate>)delegate
  684. {
  685. [self performBlock:^{
  686. // If the request wasn't generated yet, then willSendRequest was not called. This appears to be an inconsistency in documentation
  687. // and behavior.
  688. NSURLRequest *request = [self requestForTask:downloadTask];
  689. if (!request) {
  690. request = downloadTask.currentRequest;
  691. [self setRequest:request forTask:downloadTask];
  692. NSString *requestID = [self requestIDForTask:downloadTask];
  693. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestID request:request redirectResponse:nil requestMechanism:[NSString stringWithFormat:@"NSURLSessionDownloadTask (delegate: %@)", [delegate class]]];
  694. NSMutableData *dataAccumulator = nil;
  695. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger) totalBytesExpectedToWrite];
  696. [self setAccumulatedData:dataAccumulator forTask:downloadTask];
  697. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID request:request response:downloadTask.response];
  698. }
  699. NSString *requestID = [self requestIDForTask:downloadTask];
  700. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID request:downloadTask.currentRequest dataLength:bytesWritten];
  701. }];
  702. }
  703. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  704. {
  705. [self performBlock:^{
  706. NSString *requestID = [self requestIDForTask:downloadTask];
  707. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID request:downloadTask.currentRequest responseBody:data];
  708. [self taskFinished:downloadTask];
  709. }];
  710. }
  711. @end