FLEXNetworkObserver.m 45 KB

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