FLEXNetworkObserver.m 46 KB

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