FLEXNetworkObserver.m 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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:didReceiveResponse:),
  178. @selector(URLSession:dataTask:didReceiveResponse:completionHandler:),
  179. @selector(URLSession:task:didCompleteWithError:),
  180. @selector(URLSession:downloadTask:didFinishDownloadingToURL:)
  181. };
  182. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  183. Class *classes = NULL;
  184. int numClasses = objc_getClassList(NULL, 0);
  185. if (numClasses > 0) {
  186. classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
  187. numClasses = objc_getClassList(classes, numClasses);
  188. for (NSInteger classIndex = 0; classIndex < numClasses; ++classIndex) {
  189. Class class = classes[classIndex];
  190. if (class == [FLEXNetworkObserver class]) {
  191. continue;
  192. }
  193. // Use the runtime API rather than the methods on NSObject to avoid sending messages to
  194. // classes we're not interested in swizzling. Otherwise we hit +initialize on all classes.
  195. for (int selectorIndex = 0; selectorIndex < numSelectors; ++selectorIndex) {
  196. if (class_getInstanceMethod(class, selectors[selectorIndex])) {
  197. [self injectIntoDelegateClass:class];
  198. break;
  199. }
  200. }
  201. }
  202. free(classes);
  203. }
  204. [self injectIntoNSURLConnectionCancel];
  205. [self injectIntoNSURLSessionTaskResume];
  206. });
  207. }
  208. + (void)injectIntoDelegateClass:(Class)cls
  209. {
  210. // Connections
  211. [self injectWillSendRequestIntoDelegateClass:cls];
  212. [self injectDidReceiveDataIntoDelegateClass:cls];
  213. [self injectDidReceiveResponseIntoDelegateClass:cls];
  214. [self injectDidFinishLoadingIntoDelegateClass:cls];
  215. [self injectDidFailWithErrorIntoDelegateClass:cls];
  216. // Sessions
  217. [self injectTaskWillPerformHTTPRedirectionIntoDelegateClass:cls];
  218. [self injectTaskDidReceiveDataIntoDelegateClass:cls];
  219. [self injectTaskDidReceiveResponseIntoDelegateClass:cls];
  220. [self injectTaskDidCompleteWithErrorIntoDelegateClass:cls];
  221. [self injectRespondsToSelectorIntoDelegateClass:cls];
  222. // Data tasks
  223. [self injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:cls];
  224. // Download tasks
  225. [self injectDownloadTaskDidWriteDataIntoDelegateClass:cls];
  226. [self injectDownloadTaskDidFinishDownloadingIntoDelegateClass:cls];
  227. }
  228. + (void)injectIntoNSURLConnectionCancel
  229. {
  230. Class class = [NSURLConnection class];
  231. SEL selector = @selector(cancel);
  232. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  233. Method originalCancel = class_getInstanceMethod(class, selector);
  234. void (^swizzleBlock)(NSURLConnection *) = ^(NSURLConnection *slf) {
  235. [[FLEXNetworkObserver sharedObserver] connectionWillCancel:slf];
  236. ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector);
  237. };
  238. IMP implementation = imp_implementationWithBlock(swizzleBlock);
  239. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalCancel));
  240. Method newCancel = class_getInstanceMethod(class, swizzledSelector);
  241. method_exchangeImplementations(originalCancel, newCancel);
  242. }
  243. + (void)injectIntoNSURLSessionTaskResume
  244. {
  245. Class class = [NSURLSessionTask class];
  246. SEL selector = @selector(resume);
  247. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  248. Method originalResume = class_getInstanceMethod(class, selector);
  249. void (^swizzleBlock)(NSURLSessionTask *) = ^(NSURLSessionTask *slf) {
  250. [[FLEXNetworkObserver sharedObserver] URLSessionTaskWillResume:slf];
  251. ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector);
  252. };
  253. IMP implementation = imp_implementationWithBlock(swizzleBlock);
  254. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalResume));
  255. Method newResume = class_getInstanceMethod(class, swizzledSelector);
  256. method_exchangeImplementations(originalResume, newResume);
  257. }
  258. + (void)injectWillSendRequestIntoDelegateClass:(Class)cls
  259. {
  260. SEL selector = @selector(connection:willSendRequest:redirectResponse:);
  261. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  262. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  263. if (!protocol) {
  264. protocol = @protocol(NSURLConnectionDelegate);
  265. }
  266. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  267. typedef NSURLRequest *(^NSURLConnectionWillSendRequestBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response);
  268. NSURLConnectionWillSendRequestBlock undefinedBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  269. [[FLEXNetworkObserver sharedObserver] connection:connection willSendRequest:request redirectResponse:response delegate:slf];
  270. return request;
  271. };
  272. NSURLConnectionWillSendRequestBlock implementationBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  273. __block NSURLRequest *returnValue = nil;
  274. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  275. undefinedBlock(slf, connection, request, response);
  276. } originalImplementationBlock:^{
  277. returnValue = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, connection, request, response);
  278. }];
  279. return returnValue;
  280. };
  281. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  282. }
  283. + (void)injectDidReceiveResponseIntoDelegateClass:(Class)cls
  284. {
  285. SEL selector = @selector(connection:didReceiveResponse:);
  286. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  287. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  288. if (!protocol) {
  289. protocol = @protocol(NSURLConnectionDelegate);
  290. }
  291. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  292. typedef void (^NSURLConnectionDidReceiveResponseBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response);
  293. NSURLConnectionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  294. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveResponse:response delegate:slf];
  295. };
  296. NSURLConnectionDidReceiveResponseBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  297. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  298. undefinedBlock(slf, connection, response);
  299. } originalImplementationBlock:^{
  300. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, response);
  301. }];
  302. };
  303. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  304. }
  305. + (void)injectDidReceiveDataIntoDelegateClass:(Class)cls
  306. {
  307. SEL selector = @selector(connection:didReceiveData:);
  308. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  309. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  310. if (!protocol) {
  311. protocol = @protocol(NSURLConnectionDelegate);
  312. }
  313. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  314. typedef void (^NSURLConnectionDidReceiveDataBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data);
  315. NSURLConnectionDidReceiveDataBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  316. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveData:data delegate:slf];
  317. };
  318. NSURLConnectionDidReceiveDataBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  319. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  320. undefinedBlock(slf, connection, data);
  321. } originalImplementationBlock:^{
  322. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, data);
  323. }];
  324. };
  325. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  326. }
  327. + (void)injectDidFinishLoadingIntoDelegateClass:(Class)cls
  328. {
  329. SEL selector = @selector(connectionDidFinishLoading:);
  330. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  331. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  332. if (!protocol) {
  333. protocol = @protocol(NSURLConnectionDelegate);
  334. }
  335. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  336. typedef void (^NSURLConnectionDidFinishLoadingBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection);
  337. NSURLConnectionDidFinishLoadingBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  338. [[FLEXNetworkObserver sharedObserver] connectionDidFinishLoading:connection delegate:slf];
  339. };
  340. NSURLConnectionDidFinishLoadingBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  341. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  342. undefinedBlock(slf, connection);
  343. } originalImplementationBlock:^{
  344. ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSelector, connection);
  345. }];
  346. };
  347. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  348. }
  349. + (void)injectDidFailWithErrorIntoDelegateClass:(Class)cls
  350. {
  351. SEL selector = @selector(connection:didFailWithError:);
  352. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  353. Protocol *protocol = @protocol(NSURLConnectionDelegate);
  354. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  355. typedef void (^NSURLConnectionDidFailWithErrorBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error);
  356. NSURLConnectionDidFailWithErrorBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  357. [[FLEXNetworkObserver sharedObserver] connection:connection didFailWithError:error delegate:slf];
  358. };
  359. NSURLConnectionDidFailWithErrorBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  360. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  361. undefinedBlock(slf, connection, error);
  362. } originalImplementationBlock:^{
  363. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, error);
  364. }];
  365. };
  366. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  367. }
  368. + (void)injectTaskWillPerformHTTPRedirectionIntoDelegateClass:(Class)cls
  369. {
  370. SEL selector = @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:);
  371. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  372. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  373. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  374. typedef void (^NSURLSessionWillPerformHTTPRedirectionBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *));
  375. NSURLSessionWillPerformHTTPRedirectionBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  376. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task willPerformHTTPRedirection:response newRequest:newRequest completionHandler:completionHandler delegate:slf];
  377. };
  378. NSURLSessionWillPerformHTTPRedirectionBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  379. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  380. undefinedBlock(slf, session, task, response, newRequest, completionHandler);
  381. } originalImplementationBlock:^{
  382. ((id(*)(id, SEL, id, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, task, response, newRequest, completionHandler);
  383. }];
  384. };
  385. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  386. }
  387. + (void)injectTaskDidReceiveDataIntoDelegateClass:(Class)cls
  388. {
  389. SEL selector = @selector(URLSession:dataTask:didReceiveData:);
  390. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  391. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  392. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  393. typedef void (^NSURLSessionDidReceiveDataBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
  394. NSURLSessionDidReceiveDataBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  395. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveData:data delegate:slf];
  396. };
  397. NSURLSessionDidReceiveDataBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  398. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  399. undefinedBlock(slf, session, dataTask, data);
  400. } originalImplementationBlock:^{
  401. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, data);
  402. }];
  403. };
  404. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  405. }
  406. + (void)injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:(Class)cls
  407. {
  408. SEL selector = @selector(URLSession:dataTask:didBecomeDownloadTask:);
  409. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  410. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  411. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  412. typedef void (^NSURLSessionDidBecomeDownloadTaskBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
  413. NSURLSessionDidBecomeDownloadTaskBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) {
  414. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didBecomeDownloadTask:downloadTask delegate:slf];
  415. };
  416. NSURLSessionDidBecomeDownloadTaskBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) {
  417. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  418. undefinedBlock(slf, session, dataTask, downloadTask);
  419. } originalImplementationBlock:^{
  420. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, downloadTask);
  421. }];
  422. };
  423. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  424. }
  425. + (void)injectTaskDidReceiveResponseIntoDelegateClass:(Class)cls
  426. {
  427. SEL selector = @selector(URLSession:dataTask:didReceiveResponse:completionHandler:);
  428. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  429. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  430. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  431. typedef void (^NSURLSessionDidReceiveResponseBlock)(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition));
  432. NSURLSessionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  433. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler delegate:slf];
  434. };
  435. NSURLSessionDidReceiveResponseBlock implementationBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  436. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  437. undefinedBlock(slf, session, dataTask, response, completionHandler);
  438. } originalImplementationBlock:^{
  439. ((void(*)(id, SEL, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, dataTask, response, completionHandler);
  440. }];
  441. };
  442. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  443. }
  444. + (void)injectTaskDidCompleteWithErrorIntoDelegateClass:(Class)cls
  445. {
  446. SEL selector = @selector(URLSession:task:didCompleteWithError:);
  447. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  448. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  449. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  450. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error);
  451. NSURLSessionTaskDidCompleteWithErrorBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  452. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didCompleteWithError:error delegate:slf];
  453. };
  454. NSURLSessionTaskDidCompleteWithErrorBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  455. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  456. undefinedBlock(slf, session, task, error);
  457. } originalImplementationBlock:^{
  458. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, error);
  459. }];
  460. };
  461. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  462. }
  463. // Used for overriding AFNetworking behavior
  464. + (void)injectRespondsToSelectorIntoDelegateClass:(Class)cls
  465. {
  466. SEL selector = @selector(respondsToSelector:);
  467. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  468. //Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  469. Method method = class_getInstanceMethod(cls, selector);
  470. struct objc_method_description methodDescription = *method_getDescription(method);
  471. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id slf, SEL sel);
  472. BOOL (^undefinedBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id slf, SEL sel) {
  473. return YES;
  474. };
  475. BOOL (^implementationBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id <NSURLSessionTaskDelegate> slf, SEL sel) {
  476. if (sel == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
  477. return undefinedBlock(slf, sel);
  478. }
  479. return ((BOOL(*)(id, SEL, SEL))objc_msgSend)(slf, swizzledSelector, sel);
  480. };
  481. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  482. }
  483. + (void)injectDownloadTaskDidFinishDownloadingIntoDelegateClass:(Class)cls
  484. {
  485. SEL selector = @selector(URLSession:downloadTask:didFinishDownloadingToURL:);
  486. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  487. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  488. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  489. typedef void (^NSURLSessionDownloadTaskDidFinishDownloadingBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location);
  490. NSURLSessionDownloadTaskDidFinishDownloadingBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  491. NSData *data = [NSData dataWithContentsOfFile:location.relativePath];
  492. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didFinishDownloadingToURL:location data:data delegate:slf];
  493. };
  494. NSURLSessionDownloadTaskDidFinishDownloadingBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  495. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  496. undefinedBlock(slf, session, task, location);
  497. } originalImplementationBlock:^{
  498. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, location);
  499. }];
  500. };
  501. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  502. }
  503. + (void)injectDownloadTaskDidWriteDataIntoDelegateClass:(Class)cls
  504. {
  505. SEL selector = @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:);
  506. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  507. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  508. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  509. typedef void (^NSURLSessionDownloadTaskDidWriteDataBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
  510. NSURLSessionDownloadTaskDidWriteDataBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  511. [[FLEXNetworkObserver sharedObserver] URLSession:session downloadTask:task didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite delegate:slf];
  512. };
  513. NSURLSessionDownloadTaskDidWriteDataBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  514. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  515. undefinedBlock(slf, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  516. } originalImplementationBlock:^{
  517. ((void(*)(id, SEL, id, id, int64_t, int64_t, int64_t))objc_msgSend)(slf, swizzledSelector, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  518. }];
  519. };
  520. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  521. }
  522. #pragma mark - Initialization
  523. - (id)init
  524. {
  525. self = [super init];
  526. if (!self) {
  527. return nil;
  528. }
  529. _connectionStates = [[NSMutableDictionary alloc] init];
  530. _queue = dispatch_queue_create("com.flex.FLEXNetworkObserver", DISPATCH_QUEUE_SERIAL);
  531. return self;
  532. }
  533. #pragma mark - Private Methods
  534. - (void)performBlock:(dispatch_block_t)block
  535. {
  536. if (self.isEnabled) {
  537. dispatch_async(_queue, block);
  538. }
  539. }
  540. #pragma mark - Private Methods (Connections)
  541. - (FLEXInternalRequestState *)requestStateForConnection:(NSURLConnection *)connection
  542. {
  543. NSValue *key = [NSValue valueWithNonretainedObject:connection];
  544. FLEXInternalRequestState *state = [_connectionStates objectForKey:key];
  545. if (!state) {
  546. state = [[FLEXInternalRequestState alloc] init];
  547. state.requestID = [[self class] nextRequestID];
  548. [_connectionStates setObject:state forKey:key];
  549. }
  550. return state;
  551. }
  552. - (NSString *)requestIDForConnection:(NSURLConnection *)connection
  553. {
  554. return [self requestStateForConnection:connection].requestID;
  555. }
  556. - (void)setRequest:(NSURLRequest *)request forConnection:(NSURLConnection *)connection
  557. {
  558. [self requestStateForConnection:connection].request = request;
  559. }
  560. - (NSURLRequest *)requestForConnection:(NSURLConnection *)connection
  561. {
  562. return [self requestStateForConnection:connection].request;
  563. }
  564. - (void)setAccumulatedData:(NSMutableData *)data forConnection:(NSURLConnection *)connection
  565. {
  566. FLEXInternalRequestState *requestState = [self requestStateForConnection:connection];
  567. requestState.dataAccumulator = data;
  568. }
  569. - (void)addAccumulatedData:(NSData *)data forConnection:(NSURLConnection *)connection
  570. {
  571. NSMutableData *dataAccumulator = [self requestStateForConnection:connection].dataAccumulator;
  572. [dataAccumulator appendData:data];
  573. }
  574. - (NSData *)accumulatedDataForConnection:(NSURLConnection *)connection
  575. {
  576. return [self requestStateForConnection:connection].dataAccumulator;
  577. }
  578. // This removes storing the accumulated request/response from the dictionary so we can release connection
  579. - (void)connectionFinished:(NSURLConnection *)connection
  580. {
  581. NSValue *key = [NSValue valueWithNonretainedObject:connection];
  582. [_connectionStates removeObjectForKey:key];
  583. }
  584. #pragma mark - Private Methods (Tasks)
  585. - (FLEXInternalRequestState *)requestStateForTask:(NSURLSessionTask *)task
  586. {
  587. NSValue *key = [NSValue valueWithNonretainedObject:task];
  588. FLEXInternalRequestState *state = [_connectionStates objectForKey:key];
  589. if (!state) {
  590. state = [[FLEXInternalRequestState alloc] init];
  591. state.requestID = [[self class] nextRequestID];
  592. [_connectionStates setObject:state forKey:key];
  593. }
  594. return state;
  595. }
  596. - (void)setRequestState:(FLEXInternalRequestState *)state forTask:(NSURLSessionTask *)task
  597. {
  598. NSValue *key = [NSValue valueWithNonretainedObject:task];
  599. [_connectionStates setObject:state forKey:key];
  600. }
  601. - (NSString *)requestIDForTask:(NSURLSessionTask *)task
  602. {
  603. return [self requestStateForTask:task].requestID;
  604. }
  605. - (void)setRequest:(NSURLRequest *)request forTask:(NSURLSessionTask *)task
  606. {
  607. [self requestStateForTask:task].request = request;
  608. }
  609. - (NSURLRequest *)requestForTask:(NSURLSessionTask *)task
  610. {
  611. return [self requestStateForTask:task].request;
  612. }
  613. - (void)setAccumulatedData:(NSMutableData *)data forTask:(NSURLSessionTask *)task
  614. {
  615. FLEXInternalRequestState *requestState = [self requestStateForTask:task];
  616. requestState.dataAccumulator = data;
  617. }
  618. - (void)addAccumulatedData:(NSData *)data forTask:(NSURLSessionTask *)task
  619. {
  620. NSMutableData *dataAccumulator = [self requestStateForTask:task].dataAccumulator;
  621. [dataAccumulator appendData:data];
  622. }
  623. - (NSData *)accumulatedDataForTask:(NSURLSessionTask *)task
  624. {
  625. return [self requestStateForTask:task].dataAccumulator;
  626. }
  627. // This removes storing the accumulated request/response from the dictionary so we can release task
  628. - (void)taskFinished:(NSURLSessionTask *)task
  629. {
  630. NSValue *key = [NSValue valueWithNonretainedObject:task];
  631. [_connectionStates removeObjectForKey:key];
  632. }
  633. @end
  634. @implementation FLEXNetworkObserver (NSURLConnectionHelpers)
  635. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  636. {
  637. [self performBlock:^{
  638. [self setRequest:request forConnection:connection];
  639. NSString *requestId = [self requestIDForConnection:connection];
  640. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestId request:request redirectResponse:response];
  641. NSString *mechanism = [NSString stringWithFormat:@"NSURLConnection (delegate: %@)", [delegate class]];
  642. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestId:requestId];
  643. }];
  644. }
  645. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  646. {
  647. [self performBlock:^{
  648. // If the request wasn't generated yet, then willSendRequest was not called. This appears to be an inconsistency in documentation
  649. // and behavior.
  650. NSURLRequest *request = [self requestForConnection:connection];
  651. if (!request) {
  652. request = connection.currentRequest;
  653. [self setRequest:request forConnection:connection];
  654. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForConnection:connection] request:request redirectResponse:nil];
  655. }
  656. NSMutableData *dataAccumulator = nil;
  657. if (response.expectedContentLength < 0) {
  658. dataAccumulator = [[NSMutableData alloc] init];
  659. } else {
  660. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  661. }
  662. [self setAccumulatedData:dataAccumulator forConnection:connection];
  663. NSString *requestID = [self requestIDForConnection:connection];
  664. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:response];
  665. }];
  666. }
  667. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id<NSURLConnectionDelegate>)delegate
  668. {
  669. // Just to be safe since we're doing this async
  670. data = [data copy];
  671. [self performBlock:^{
  672. [self addAccumulatedData:data forConnection:connection];
  673. if ([self accumulatedDataForConnection:connection] == nil) return;
  674. NSString *requestID = [self requestIDForConnection:connection];
  675. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:data.length];
  676. }];
  677. }
  678. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id<NSURLConnectionDelegate>)delegate
  679. {
  680. [self performBlock:^{
  681. NSString *requestID = [self requestIDForConnection:connection];
  682. NSData *accumulatedData = [self accumulatedDataForConnection:connection];
  683. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID responseBody:accumulatedData];
  684. [self connectionFinished:connection];
  685. }];
  686. }
  687. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id<NSURLConnectionDelegate>)delegate
  688. {
  689. [self performBlock:^{
  690. NSString *requestID = [self requestIDForConnection:connection];
  691. // Errors can occur prior to the willSendRequest:... delegate call. In those cases, let the recorder know about the request before logging the failure.
  692. NSURLRequest *request = [self requestForConnection:connection];
  693. if (!request) {
  694. request = connection.currentRequest;
  695. [self setRequest:request forConnection:connection];
  696. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestID request:request redirectResponse:nil];
  697. }
  698. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestId:requestID error:error];
  699. [self connectionFinished:connection];
  700. }];
  701. }
  702. - (void)connectionWillCancel:(NSURLConnection *)connection
  703. {
  704. [self performBlock:^{
  705. // Mimic the behavior of NSURLSession which is to create an error on cancellation.
  706. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"cancelled" };
  707. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
  708. [self connection:connection didFailWithError:error delegate:nil];
  709. }];
  710. }
  711. @end
  712. @implementation FLEXNetworkObserver (NSURLSessionTaskHelpers)
  713. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  714. {
  715. [self performBlock:^{
  716. [self setRequest:request forTask:task];
  717. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForTask:task] request:request redirectResponse:response];
  718. }];
  719. }
  720. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  721. {
  722. [self performBlock:^{
  723. // willSendRequest does not exist in NSURLSession. Here's a workaround.
  724. NSURLRequest *request = [self requestForTask:dataTask];
  725. if (!request) {
  726. request = dataTask.currentRequest;
  727. [self setRequest:request forTask:dataTask];
  728. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForTask:dataTask] request:request redirectResponse:nil];
  729. }
  730. NSMutableData *dataAccumulator = nil;
  731. if (response.expectedContentLength < 0) {
  732. dataAccumulator = [[NSMutableData alloc] init];
  733. } else {
  734. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  735. }
  736. [self setAccumulatedData:dataAccumulator forTask:dataTask];
  737. NSString *requestID = [self requestIDForTask:dataTask];
  738. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDataTask (delegate: %@)", [delegate class]];
  739. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestId:requestID];
  740. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:response];
  741. }];
  742. }
  743. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask delegate:(id<NSURLSessionDelegate>)delegate
  744. {
  745. [self performBlock:^{
  746. // Update our internal accounting to reflect the task swap.
  747. FLEXInternalRequestState *state = [self requestStateForTask:dataTask];
  748. [self setRequestState:state forTask:downloadTask];
  749. [self taskFinished:dataTask];
  750. }];
  751. }
  752. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  753. {
  754. // Just to be safe since we're doing this async
  755. data = [data copy];
  756. [self performBlock:^{
  757. [self addAccumulatedData:data forTask:dataTask];
  758. if ([self accumulatedDataForTask:dataTask] == nil) return;
  759. NSString *requestID = [self requestIDForTask:dataTask];
  760. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:data.length];
  761. }];
  762. }
  763. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id<NSURLSessionDelegate>)delegate
  764. {
  765. [self performBlock:^{
  766. NSString *requestID = [self requestIDForTask:task];
  767. NSData *accumulatedData = [self accumulatedDataForTask:task];
  768. if (error) {
  769. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestId:requestID error:error];
  770. } else {
  771. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID responseBody:accumulatedData];
  772. }
  773. [self taskFinished:task];
  774. }];
  775. }
  776. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id<NSURLSessionDelegate>)delegate
  777. {
  778. [self performBlock:^{
  779. NSString *requestID = [self requestIDForTask:downloadTask];
  780. if (![[self requestStateForTask:downloadTask] dataAccumulator]) {
  781. NSMutableData *dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)totalBytesExpectedToWrite];
  782. [self setAccumulatedData:dataAccumulator forTask:downloadTask];
  783. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:downloadTask.response];
  784. }
  785. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDownloadTask (delegate: %@)", [delegate class]];
  786. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestId:requestID];
  787. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:bytesWritten];
  788. }];
  789. }
  790. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  791. {
  792. data = [data copy];
  793. [self performBlock:^{
  794. [self addAccumulatedData:data forTask:downloadTask];
  795. }];
  796. }
  797. - (void)URLSessionTaskWillResume:(NSURLSessionTask *)task
  798. {
  799. // Since resume can be called multiple times on the same task, only treat the first resume as
  800. // the equivalent to connection:willSendRequest:...
  801. [self performBlock:^{
  802. NSURLRequest *request = [self requestForTask:task];
  803. if (!request) {
  804. request = task.currentRequest;
  805. [self setRequest:request forTask:task];
  806. NSString *requestID = [self requestIDForTask:task];
  807. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestID request:request redirectResponse:nil];
  808. }
  809. }];
  810. }
  811. @end