FLEXNetworkObserver.m 49 KB

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