FLEXNetworkObserver.m 47 KB

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