FLEXNetworkObserver.m 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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. // Errors can occur prior to the willSendRequest:... delegate call. In those cases, let the recorder know about the request before logging the failure.
  710. NSURLRequest *request = [self requestForConnection:connection];
  711. if (!request) {
  712. request = connection.currentRequest;
  713. [self setRequest:request forConnection:connection];
  714. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestID request:request redirectResponse:nil];
  715. }
  716. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestId:requestID error:error];
  717. [self connectionFinished:connection];
  718. }];
  719. }
  720. - (void)connectionWillCancel:(NSURLConnection *)connection
  721. {
  722. [self performBlock:^{
  723. // Mimic the behavior of NSURLSession which is to create an error on cancellation.
  724. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"cancelled" };
  725. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
  726. [self connection:connection didFailWithError:error delegate:nil];
  727. }];
  728. }
  729. @end
  730. @implementation FLEXNetworkObserver (NSURLSessionTaskHelpers)
  731. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  732. {
  733. [self performBlock:^{
  734. [self setRequest:request forTask:task];
  735. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForTask:task] request:request redirectResponse:response];
  736. }];
  737. }
  738. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  739. {
  740. [self performBlock:^{
  741. // willSendRequest does not exist in NSURLSession. Here's a workaround.
  742. NSURLRequest *request = [self requestForTask:dataTask];
  743. if (!request) {
  744. request = dataTask.currentRequest;
  745. [self setRequest:request forTask:dataTask];
  746. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForTask:dataTask] request:request redirectResponse:nil];
  747. }
  748. NSMutableData *dataAccumulator = nil;
  749. if (response.expectedContentLength < 0) {
  750. dataAccumulator = [[NSMutableData alloc] init];
  751. } else {
  752. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  753. }
  754. [self setAccumulatedData:dataAccumulator forTask:dataTask];
  755. NSString *requestID = [self requestIDForTask:dataTask];
  756. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDataTask (delegate: %@)", [delegate class]];
  757. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestId:requestID];
  758. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:response];
  759. }];
  760. }
  761. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask delegate:(id<NSURLSessionDelegate>)delegate
  762. {
  763. [self performBlock:^{
  764. // Update our internal accounting to reflect the task swap.
  765. FLEXInternalRequestState *state = [self requestStateForTask:dataTask];
  766. [self setRequestState:state forTask:downloadTask];
  767. [self taskFinished:dataTask];
  768. }];
  769. }
  770. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  771. {
  772. // Just to be safe since we're doing this async
  773. data = [data copy];
  774. [self performBlock:^{
  775. [self addAccumulatedData:data forTask:dataTask];
  776. if ([self accumulatedDataForTask:dataTask] == nil) return;
  777. NSString *requestID = [self requestIDForTask:dataTask];
  778. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:data.length];
  779. }];
  780. }
  781. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id<NSURLSessionDelegate>)delegate
  782. {
  783. [self performBlock:^{
  784. NSString *requestID = [self requestIDForTask:task];
  785. NSData *accumulatedData = [self accumulatedDataForTask:task];
  786. if (error) {
  787. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestId:requestID error:error];
  788. } else {
  789. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID responseBody:accumulatedData];
  790. }
  791. [self taskFinished:task];
  792. }];
  793. }
  794. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id<NSURLSessionDelegate>)delegate
  795. {
  796. [self performBlock:^{
  797. NSString *requestID = [self requestIDForTask:downloadTask];
  798. if (![[self requestStateForTask:downloadTask] dataAccumulator]) {
  799. NSMutableData *dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)totalBytesExpectedToWrite];
  800. [self setAccumulatedData:dataAccumulator forTask:downloadTask];
  801. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:downloadTask.response];
  802. }
  803. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDownloadTask (delegate: %@)", [delegate class]];
  804. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestId:requestID];
  805. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:bytesWritten];
  806. }];
  807. }
  808. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  809. {
  810. data = [data copy];
  811. [self performBlock:^{
  812. [self addAccumulatedData:data forTask:downloadTask];
  813. }];
  814. }
  815. - (void)URLSessionTaskWillResume:(NSURLSessionTask *)task
  816. {
  817. // Since resume can be called multiple times on the same task, only treat the first resume as
  818. // the equivalent to connection:willSendRequest:...
  819. [self performBlock:^{
  820. NSURLRequest *request = [self requestForTask:task];
  821. if (!request) {
  822. request = task.currentRequest;
  823. [self setRequest:request forTask:task];
  824. NSString *requestID = [self requestIDForTask:task];
  825. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestID request:request redirectResponse:nil];
  826. }
  827. }];
  828. }
  829. @end