FLEXNetworkObserver.m 43 KB

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