FLEXNetworkObserver.m 44 KB

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