FLEXNetworkObserver.m 44 KB

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